1

I have a page like this that page1.php codes will load with ajax in that:

...
<div id="myContent" >
<!-- ajax content load here -->
</div>
...

and my ajax codes are:

 $.ajax({
        type: 'post',
        url: 'codes/page.php',
        async: false,
        data: formDatas
        , success: function (response) {
            document.getElementById('myContent').innerHTML = response; // response contains page1.php codes
            }
        }
    });

and these datas will load from page1.php:

<script>
    alert("hello");
</script>

<div>
    ...
</div>

Now my problem is that when I load page1.php directly, this alerts "hello". But when I load this contents via ajax , scripts not works and nothing alerted

How do I do to running these scripts after loading datas in myContent div.

thank you all

Sadegh
  • 862
  • 1
  • 8
  • 23

2 Answers2

2

For browsers that follow the HTML5 spec (i.e. all current, major browsers), script elements inserted using innerHTML do not execute when they are inserted.

However, if you use jQuery's .html() method, your scripts will execute:

$.ajax({
    type: 'post',
    url: 'codes/page.php',
    data: formDatas, 
    success: function (response) {
        $('#myContent').html(response);
    }
});

Working fiddle here

Dave
  • 10,748
  • 3
  • 43
  • 54
1

You've got an extra closing bracket in there that's likely causing an error (right beneath the document.getElementById). Also, since you're using jQuery, it's better to use the jQuery selector syntax and html function.

Try this instead of your current code...

$.ajax({
    type: 'post',
    url: 'codes/page.php',
    async: false,
    data: formDatas,
    success: function (response) {
        $('#myContent').html(response); //response contains page1.php codes
    }
});
Jacob
  • 383
  • 1
  • 5
  • 11