Call Js Function After Div Is Loaded

How to call a function after a div is ready?

You can use recursion here to do this. For example:

jQuery(document).ready(checkContainer);

function checkContainer () {
if($('#divIDer').is(':visible'))){ //if the container is visible on the page
createGrid(); //Adds a grid to the html
} else {
setTimeout(checkContainer, 50); //wait 50 ms, then try again
}
}

Basically, this function will check to make sure that the element exists and is visible. If it is, it will run your createGrid() function. If not, it will wait 50ms and try again.

Note:: Ideally, you would just use the callback function of your AJAX call to know when the container was appended, but this is a brute force, standalone approach. :)

Run JS after div contents loaded from AJAX

Note that success and failure are options that you should provide to the $.ajax call, not the returned promise. Also, bind is deprecated in favour of on since jQuery 1.7. Finally, you need to give the value that you're posting to your PHP page a key so that it can be retrieved via $_POST. Try this:

$("#CardSearch").on('submit', function(e) {
e.preventDefault();

$.ajax({
method: "POST",
url: "synergies.php",
data: {
CardName: $('#CardName').val()
},
success: function(data) {
$("#Results").html(data);
},
complete: function() {
alert("div updated!"); //Trying to run JS code AFTER div finishes loading
}
})
});

You can then retrieve the value sent in your synergies.php file using $_POST['CardName'].

If you prefer to use the method provided by the returned promise, you can do that like the below, although the result is identical.

$("#CardSearch").on('submit', function(e) {
e.preventDefault();

$.ajax({
method: "POST",
url: "synergies.php",
data: {
CardName: $('#CardName').val()
}
}).done(function(data) {
$("#Results").html(data);
}).always(function() {
alert("div updated!");
})
});


Related Topics



Leave a reply



Submit