pgiouroukis
pgiouroukis

Reputation: 61

AJAX delaying the execution of next lines

Given the following code, can anyone help me understand why the first alert is executed after the second one? I believe this happens because ajax has a small delay untill it fetches the data, correct me if i am wrong.Thanks in advance.

Javascript code:

window.onload = function() {
arry = new Array();
jQuery.ajax({    
    type: "GET",
    url: "index.php?op=17&id=@@postID@@&action=fetch",   
    dataType: "text",
    success: function(response){    
        var e = response;
        console.log(JSON.parse(e));
        arry = JSON.parse(e)
        alert(e); //1st alert
    }
}); 
alert("test") //2nd alert
}

Upvotes: 4

Views: 63

Answers (2)

Me1o
Me1o

Reputation: 1629

yous first array is inside the success event of the AJAX call which (the success function) gets registered, skipped and called back only when the response of the ajax call is ready..

Upvotes: 0

BenM
BenM

Reputation: 53238

The first "A" in AJAX stands for asynchronous. That means that it is not blocking in your code, so the alert('test') is called immediately after your AJAX request, whereas alert(e) is only called once the AJAX request has received a successful response from the server.

The 'small delay' that you mention is not such, but rather the time it takes for the server to execute whatever code and return a response.

If you absolutely need the request to be handled synchronously, you can pass the async property to the AJAX call as follows:

window.onload = function() {
    var arry = [ ];

   jQuery.ajax({    
       type: "GET",
        url: "index.php?op=17&id=@@postID@@&action=fetch",   
        dataType: "json",
        async: false
    }).done(function(response) {
        arry = response
        alert(response); //1st alert
    });

    alert("test") //2nd alert
}

Notice that I have updated the code somewhat to use the done() promise. Also, specifying dataType: "json" negates the need to call JSON.parse() on the response text.

Upvotes: 5

Related Questions