Dynamically reload elements and read their new attributes in JQuery

I have an Ajax call that returns a piece of html code that should replace the 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 were running synchronously).

The only workaround I have found is to set the timer, but the timer delay time should be relatively high (300ms) to ensure it always runs correctly. What is the correct way to do this?

Here is pseudocode for what I have right now. It works, but the 300ms latency is terrible.

$.post( "ajax/test.html", function( newCode ) {
    $("#myDynamicDiv").html(newCode);
    setTimeout(function(){
        //Use the data that was just stored in #myDynamicDiv
    },300);
});

      

+3


source to share


2 answers


For me I use .promise().done()

, maybe it will work with you

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

      



Edit : someone who will come here later. Until my code works with Mohasen , he finds the solution himself .. Find his answer below

+2


source


I accepted Mohamed-Yousef's answer, but since it did not include the complete answer, here is the complete version of what I ended up doing:

JQuery ajax call always returns a "Deferred" object when called. You can use this "then ()" method to start objects after the ajax call completes. 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.
});

      

+1


source







All Articles