Shahzeb Khan
Shahzeb Khan

Reputation: 3642

function contents execution not in order

i have a java script function

function myfunction() {

    var url = location.href;
    var ajaxRespose;

        $.ajax({
            type:"GET",
            url: url,
            cache:false,
            dataType: "text",
            success: function(response) {
                var data = $.parseJSON(response);
                ajaxRespose = data;
                console.debug("ajaxRespose ==>:"+ajaxRespose);
            }
        });
        console.debug("first ajaxRespose: " +ajaxRespose);
    }
    return false;
}

on my console (firbug) i get :

first ajaxRespose: undefined

ajaxRespose ==>:[object Object]

My question is, why the ajax call execute after the "first" console.debug. PS: i have simplified the function, (function works ok, but problem is in sequence of execution)

Upvotes: 0

Views: 45

Answers (3)

bipen
bipen

Reputation: 36551

That is beacuse Ajax is Asynchronus....works happens “in parallel.”.. so when your Ajax call is getting executed, the other codes get executed parallely... the only way to make it work is to define it inside the callback function of ajax.callback function is executed when ajax call is completed thus getting the ajaxRespose in it

Upvotes: 1

Amy
Amy

Reputation: 7496

Because $.ajax() is asynchronous, the sequence of events happen like this:

$.ajax(...);   // executes AJAX request
console.debug("first ajaxResponse:" + ajaxRespose);   // undefined

/* some time later, we receive AJAX response */

// it executes the success function from the original AJAX request
console.debug("ajaxRespose ==>:"+ajaxRespose);  // [object Object]

Upvotes: 1

Kaloyan
Kaloyan

Reputation: 7352

Because AJAX is asynchronous (hence the name). The console log which logs "first ajaxRespose" is being executed before the AJAX request is completed and that's why you get undefined. Then the AJAX request completes and you get the response.

Upvotes: 1

Related Questions