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
How to Add Many Functions in One Ng-Click
How to Check If String Contains Substring
How to Round a Number in JavaScript? .Tofixed() Returns a String
How to Convert JSON Object to JavaScript Array
Proper Use of Const for Defining Functions
Reactjs Setstate() with a Dynamic Key Name
React.Js: Onchange Event for Contenteditable
Associative Array Versus Object in JavaScript
How to Download File from Server
Check If Object Is a Jquery Object
Why Do We Need to Install Gulp Globally and Locally
JavaScript Infinitely Looping Slideshow with Delays
Fix Node Position in D3 Force Directed Layout
Why Does JavaScript Hoist Variables
How to Sort Numbers Correctly with Array.Sort()
"Var" or No "Var" in JavaScript's "For-In" Loop