Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically reload elements and read their new attributes in JQuery

I have an Ajax call that returns a piece of html code that is supposed to replace old html code on the page, giving them new attributes. After I successfully dynamically change my elements, I want to run another piece of JS code that reads and uses some of the attributes of the dynamically reloaded elements. However, JS prefers to read the old data (as if it's running synchronously).

The only workaround I've found is to set a timer, but the timer's delay time has to be relatively high (300 ms) to guarantee that it's always done correctly. What is the right way to do this?

Here is a pseudo-code for what I have right now. It works but the 300ms delay time is terrible.

$.post( "ajax/test.html", function( newCode ) {
    $("#myDynamicDiv").html(newCode);
    setTimeout(function(){
        //Use the data that was just stored in #myDynamicDiv
    },300);
});
like image 302
Roozbehan Avatar asked Nov 28 '25 22:11

Roozbehan


2 Answers

For me I use .promise().done() may be it'll work with you

$("#myDynamicDiv").html(newCode).promise().done(function(){
  // your code here
});

Edit: To someone who'll comes here later ..While my code isn't working with Mohasen he find a solution himself .. Please find his answer below

like image 109
Mohamed-Yousef Avatar answered Nov 30 '25 11:11

Mohamed-Yousef


I accepted Mohamed-Yousef's answer, but since that did not include the full answer, here is the full version of what I eventually did:

A JQuery ajax call always returns a "Deferred" object when it's called. You can use this object's "then()" method to run things after the ajax call is finished. Here is the code:

dfrd = $.post( "ajax/test.html", function( newCode ) {
    $("#myDynamicDiv").html(newCode);
});

dfrd.then(function(){
    //Anything that is here is guaranteed to happen after the Ajax call is done.
});
like image 38
Roozbehan Avatar answered Nov 30 '25 12:11

Roozbehan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!