Jquery .Load()/.Ajax() Not Executing JavaScript in Returned HTML After Appended

jQuery .load() / .ajax() not executing javascript in returned HTML after appended

When load() is used with a fragment selector the script element will be stripped out before the fragment is added thus the script will not get executed.

When calling .load() using a URL without a suffixed selector
expression, the content is passed to .html() prior to scripts being
removed. This executes the script blocks before they are discarded. If
.load() is called with a selector expression appended to the URL,
however, the scripts are stripped out prior to the DOM being updated,
and thus are not executed. An example of both cases can be seen below:

So Try

$.get('partial.html', function(result){
$result = $(result);

$result.find('#content').appendTo('#new_content');
$result.find('script').appendTo('#new_content');
}, 'html');

Demo: Fiddle

AJAX appended content does not execute Javascript

I apparently, solved this problem by running the necessary javascript code on the success function

$.ajax({
type: "get",
url: "/content",
data: {
name: {{ name }}
},
success: function(data) {
$("#appendsection").append(data);
//execute necessary javascript after this
$('#sort').change(function(){
$('.section').hide();
$('#' + $(this).val()).show();
});
}
});

This might be one of the ways to delegate the javascript, but I am sure that this is not the best way to do it. But for the moment, this is the only solution that worked for me.

JS code within html returned via ajax not executing

To execute the JS code that was inserted into your html you can use the eval() function. For example: eval(document.getElementById('myJSDiv').innerHTML); Hope that's what you're looking for.

How to run AJAX loaded page scripts after loading

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
}
});


Related Topics



Leave a reply



Submit