Adam Ramadhan Adam Ramadhan - 6 months ago 17
Javascript Question

check ajax have successful appended the html with jquery

helo im trying to check if a html is appended to a id, im not sure about the best way to do this in javascript, heres a snippet what i have made so far

var appendstatus= 0;

$.ajax({
type: "GET",
url: params['content'],
dataType: 'text',
success: function(data) {
// append the html
$(params["id"]).append(data);
// is this the right way to check it ?
appendstatus= 1;
}
});

// got an 0, so its not global?
console.log(appendstatus);
// do some jobs after the html is appended on the div id


the question is what is the best way to check some data is appended in this case ?

thanks for helping out

Adam Ramadhan

Answer

Because your AJAX request is asynchronous, the console.log() happens before the response is received.

Any code that relies on the successful response must be placed in (or invoked from) the success: callback.

Order of execution:

   // STEP 1: declare and initialize the variable
var appendstatus= 0;

  // STEP 2: send the asynchronous request
$.ajax({
    type: "GET",
    url: params['content'],
    dataType: 'text',
    success: function(data) {

           // STEP 4: The response was received, so this code runs.
        $(params["id"]).append(data);

        appendstatus= 1;

        console.log( 'appendstatus from callback:', appendstatus );
    }
});

  // STEP 3: log to the console, because we're not waiting for the response
console.log(appendstatus);
Comments