Asked  7 Months ago    Answers:  5   Viewed   33 times

There's a div called "Content":

<div id="content"></div>

It should be filled with data from a PHP file, by AJAX, including a <script> tag. However, the script inside this tag is not being executed.

<div id="content"><!-- After AJAX loads the stuff that goes here -->
   <script type="text/javascript">
     //code
   </script>
   <!-- More stuff that DOES work here -->
</div>

 Answers

39

JavaScript inserted as DOM text will not execute. However, you can use the dynamic script pattern to accomplish your goal. The basic idea is to move the script that you want to execute into an external file and create a script tag when you get your Ajax response. You then set the src attribute of your script tag and voila, it loads and executes the external script.

This other StackOverflow post may also be helpful to you: Can scripts be inserted with innerHTML?.

Tuesday, June 1, 2021
 
Karsten
answered 7 Months ago
50

you are dealing with a common problem with closures. by the time your ajax request is executed, the counter "i" is already and always at it's last value (4).

you have to create a new scope for that counter, so that it doesn't happen; you can do it in two ways:

the easy way:

for(var i=1;i<5;i++){
    var counter = i;
    $.ajax({
        type: "GET",
        url: "results/result_html.php?usn="+counter+"&resultType="+resultType,
        dataType:"JSON",
        success:function(result){
            finalResult+=result;
            result=result+htmlMessage;
            $("#info").hide();
            $("#result").html(result);              
            $("#usn").attr("placeholder", "Class USN");
        }
    });
}

or the correct way:

for(var i=1;i<5;i++){
(function(counter){
    $.ajax({
        type: "GET",
        url: "results/result_html.php?usn="+"counter"+"&resultType="+resultType,
        dataType:"JSON",
        success:function(result){
            finalResult+=result;
            result=result+htmlMessage;
            $("#info").hide();
            $("#result").html(result);              
            $("#usn").attr("placeholder", "Class USN");
        }
    });
})(i);}
Saturday, May 29, 2021
 
Saxophlutist
answered 7 Months ago
40

The OP's script doesn't work in IE 7. With help from SO, here's a script that does:

exec_body_scripts: function(body_el) {
  // Finds and executes scripts in a newly added element's body.
  // Needed since innerHTML does not run scripts.
  //
  // Argument body_el is an element in the dom.

  function nodeName(elem, name) {
    return elem.nodeName && elem.nodeName.toUpperCase() ===
              name.toUpperCase();
  };

  function evalScript(elem) {
    var data = (elem.text || elem.textContent || elem.innerHTML || "" ),
        head = document.getElementsByTagName("head")[0] ||
                  document.documentElement,
        script = document.createElement("script");

    script.type = "text/javascript";
    try {
      // doesn't work on ie...
      script.appendChild(document.createTextNode(data));      
    } catch(e) {
      // IE has funky script nodes
      script.text = data;
    }

    head.insertBefore(script, head.firstChild);
    head.removeChild(script);
  };

  // main section of function
  var scripts = [],
      script,
      children_nodes = body_el.childNodes,
      child,
      i;

  for (i = 0; children_nodes[i]; i++) {
    child = children_nodes[i];
    if (nodeName(child, "script" ) &&
      (!child.type || child.type.toLowerCase() === "text/javascript")) {
          scripts.push(child);
      }
  }

  for (i = 0; scripts[i]; i++) {
    script = scripts[i];
    if (script.parentNode) {script.parentNode.removeChild(script);}
    evalScript(scripts[i]);
  }
};
Tuesday, June 1, 2021
 
turik
answered 7 Months ago
51

Same thing happened with me instead of using button use input type = button like described below -

<input type="button" id="submit" value="submit" name="submit" onclick="showHint(URL.value)"></input>

it would surely work

Thursday, August 26, 2021
 
helgoboss
answered 4 Months ago
31

Probably you should use jQuery.getScript to loading some javascript from the server and execute it.

UPDATED: In the most cases one load only the pure HTML fragment with respect of jQuery.ajax. Binding of elements to some javascript functions one do inside of success handle. All functions which one use in any event handler one loaded before (with <script> in the <head> block) on the main page (on the page which call jQuery.ajax). Then all look very clear and dynamic loading of any scripts is not needed.

Saturday, August 28, 2021
 
saad
answered 3 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :  
Share