9

I am calling a ajax method to update a div. It contains links and functions which require java script files. But these methods and functions are not getting called properly as java script files are not getting included through ajax call. For example, i am trying to call a light box function, but it gets redirected to different page and not in light box.

Thanks in advance, Anubhaw Prakash

Anubhaw
  • 101
  • 1
  • 1
  • 3
  • 1
    I had a similar question, not long ago, that I found an answer for, where I was trying to load jQuery. The info in it may help you? http://stackoverflow.com/questions/3129451/load-jquery-in-a-js-then-execute-a-script-that-depends-on-it – jasonpgignac Aug 04 '10 at 18:33

7 Answers7

2

The Ajax framework in prototype will properly execute the text content of <script> tags, but will not import new script files via <script src="somefile.js"/>. The only solution I came up with is to import all javascript files I need in the head of the page. That way the functions in the imported file are available to the inline javascript code executed in the Ajax response.

Kevin
  • 549
  • 4
  • 8
1

I had a similar problem, where I did want to postload some javascript. What I did is separating loading the html-fragment and loading the script into two calls. For loading the script I call the following function (I have JQuery handling the ajax part):

function loadModule(name, callback) {
    $.ajax({type: "POST"
          , url: "/js/" + name
          , dataType: "script"
          , success: callback
    });     
}
Daniel
  • 2,343
  • 2
  • 20
  • 24
0

I see you're using Ruby on Rails — does that mean you're using Prototype on the client? If so, Prototype's Ajax.Updater will ignore script tags that reference external files (it will evaluate script tags that have their contents inline). So to add those external files to your page, you'll have to hook into the process via the onSuccess callback, look in the responseText for script tags with src attributes, and handle those yourself. Once you've identified the relevant script tags and extracted their src attributes, you can include them by dynamically adding the scripts as described in this article from the unofficial Prototype & script.aculo.us wiki.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Hi Crowder, Thanks for the reply. I tried the code provided in article, but ajax call still does not include js files. It skips the code written under – Anubhaw Apr 20 '10 at 11:27
  • @Anubhaw: As I said, you'll have to pre-process the text to find the script tags and isolate the `src` attributes from them. The actual script won't be in the response (of course), it's just *linked to* from that text. (Or if you mean that the tags aren't in the response *at all*, that would be a server-side problem.) The technique in the linked article works fine for adding script files to a page dynamically. – T.J. Crowder Apr 20 '10 at 11:46
0

<script> tags written to innerHTML are not executed at write-time. You can do element.getElementsByTagName('script') to try to get hold of them and execute their scripts manually, but it's very ugly and not reliable.

There are tedious browser differences to do with what happens to a <script> element written to innerHTML which is then (directly or via an ancestor) re-inserted into the document. You want to avoid this sort of thing: just don't write <script>​s to innerHTML at all.

Then you also don't have to worry about executing scripts twice, which is something you never want to do with library scripts. You don't want to end up with two copies of a function/class that look the same but don't compare equal, and which hold hooks onto the page that don't play well with each other. Dynamically-inserted library scripts are a recipe for confusing failure.

Much better to include your scripts statically, and bind them to page elements manually after writing new elements to the page. If you really need to you can have your AJAX calls grab a JSON object containing both the new HTML to add and a stringful of script to execute.

bobince
  • 528,062
  • 107
  • 651
  • 834
  • Hi Bobince, Thanks for the reply. I tried replacing the script tag, but it does not include the js files in ajax request. Can you please elaborate on calling js files dynamically. Anubhaw – Anubhaw Apr 20 '10 at 11:24
  • Executing the content of scripts is annoying to do. `eval` of their `textContent` will execute in local scope, which may be no good if you are defining global functions/vars; also you would have to fetch the content of external scripts with XMLHttpRequest. (But then again, you really *don't* want to be defining globals in a script inserted at write time.) A way to execute more reliably is to take the ` – bobince Apr 20 '10 at 11:56
  • The tediousness and fragility of all this should give you a clue: this is not something HTML was designed to do; you are going against the grain trying to hack about with dynamic scripts. For sanity, keep your script code in static files and bind events to new page content manually at write-time or using delegation. – bobince Apr 20 '10 at 11:59
0

May want to try running some prepatory javascript in the :before option to setup a variable with the correct files?

SilentNot
  • 1,661
  • 1
  • 16
  • 25
0

hey i found a way to add it....:)

NOTE- this is a synchronous process so you dont have to worry about that the script is loaded or not.... the script will always load the instance u call the function and you can start using the loaded script instantaneously..

lets use these 2 functions

1) first one is the ajax function to retrieve the values where async should be true to send the request synchronously

    // AJAX FUNCTION
    function loadXMLDoc(reqt,url,reqp,cfunc,async)
    {
        var xmlhttp;
        try// code for IE7+, Firefox, Chrome, Opera, Safari
        {
            xmlhttp=new XMLHttpRequest();
        }
        catch(err)// code for IE6, IE5
        {
            try{
                xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
            }
            catch(e){
                try{
                    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
                }
                catch(E){}
            }
        }
        if(!xmlhttp)
        {
            alert("error");
        }
    xmlhttp.onreadystatechange=function(){
        if(xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            cfunc(xmlhttp.responseText);
        }
    }
    if(reqt=='GET')
    {
        url+=(reqp!=""?"?":"")+reqp;
        xmlhttp.open("GET",url,(async?false:true));
        xmlhttp.send();
    }
    else if(reqt=='POST')
    {
        xmlhttp.open("POST",url,(async?false:true));
        xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        xmlhttp.send(reqp);
    }
    else
    {
        return false;
    }
    }
    /*use this function
    loadXMLDoc(reqt,url,reqp,function(response){
    });
    */

2)then we use ajax to load the js file as string and then append it to the new script tag's innerHTML and then append it to the head section and one more thing to ensure file is already loaded i used the id of script tag as the path to the file which makes it really easy task to check for the duplicate...:)

    //add new script dynamically
    function add_script(src)
    {
        if(!document.getElementById(src))
        {
            loadXMLDoc("GET",src,"",function(jsresp){
                var head = document.getElementsByTagName("head")[0];
                var script=document.createElement("script");
                script.type='text/javascript';
                script.id=src;
                script.text=jsresp;
                head.appendChild(script);
            },true);
        }
    }

thanks for all help i used to get and will get from this site and its users for the development purposes...

regards VIPIN JAIN

Vipin Jain
  • 1,382
  • 1
  • 10
  • 19
  • I have this in my code new Ajax.Request('/products/view_favorite_list?order_no='+order_no, {asynchronous:true, evalScripts:true, insertion:'replace', parameters:'main_item_id='+ action}); I want to include js files on my favorite listing page can you guide me how where I should include above code – vasu Jan 04 '12 at 13:06
  • hey bud just copy these 2 functions and whenever u wish to add the js file just call this function like this -------------------------------------------------------- add_script("path to your js file"); -------------------------------------------------------- this will add your js file at the top of page for use immediately -------------------------------------------------------- please reply if u have more questions -------------------------------------------------------- i have edited the code right now because of some error in older browsers please copy the new code :) – Vipin Jain Jan 04 '12 at 13:48
  • I can see the request is made to js file in console but javascript is not getting called :( – vasu Jan 06 '12 at 07:29
  • no bud i m using it and i m experiencing no problems at all.... u must be mistaken... or u r not using it properly..... plz mail the process which u r using to call the elements or say the link of the application..... at joy24021987@gmail.com – Vipin Jain Jan 07 '12 at 11:00
  • Vipin - This is working on IE and chrome but on Firefox its not wokring – vasu Mar 01 '12 at 11:37
  • you are mistaking something i have tested this in all browsers – Vipin Jain Mar 04 '12 at 20:12
-2
  1. include static scripts on pages that need to use them (IE contain a lightbox, then include the lightbox script)
  2. Problem solved. Do not load scripts using AJAX
  3. Make necessary function calls to the static scripts using AJAX callbacks
Bob Gregor
  • 1,163
  • 9
  • 13