0

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)

Shahzeb Khan
  • 3,582
  • 8
  • 45
  • 79

3 Answers3

1

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.

Kaloyan
  • 7,262
  • 4
  • 32
  • 47
1

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]
Amy
  • 7,388
  • 2
  • 20
  • 31
  • thanks, i added "async:false" and now i am getting output like : ajaxRespose ==>:[object Object] first ajaxRespose: [object Object] – Shahzeb Khan Apr 02 '13 at 09:33
  • hey every body please be a good supporter with voting (up or down) the (good or bad) answers or comments. – Sina R. Apr 02 '13 at 18:16
1

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

bipen
  • 36,319
  • 9
  • 49
  • 62