views:

49

answers:

3

Hi all;

var v_name = null;

$.ajax({
    type: "GET",
    url: "Testpage.aspx",
    data: "name=test",
    dataType: "html",
    success: function(mydata) {


    $.data(document.body, 'v_name', mydata);

}
});

v_name = $.data(document.body, 'OutputGrid');

                alert(v_name);

first alert undefined before alert work why ?

A: 

To make it work, you have to place the alert() in the success function:

$.ajax({
    type: "GET",
    url: "Testpage.aspx",
    data: "name=test",
    dataType: "html",
    success: function(mydata) {
       alert(mydata);
    }
});

AJAX calls are asynchronous, and therefore JavaScript would evaluate alert(v_name); before the server responds to the AJAX call, and therefore before the success function is called.

Your AJAX applications must be designed in such a way to be driven by the AJAX response. Therefore anything you plan to do with mydata should be invoked from the success function. As a rule of the thumb, imagine that the server will take very long (such as 1 minute) to respond to the AJAX request. Your program logic should work around this concept of asynchrony.

Daniel Vassallo
A: 
$.ajax({
    type: "GET",
    url: "Testpage.aspx",
    data: "name=test",
    dataType: "html",
    success: function(mydata) {

       alert(mydata);

    }
});
Mailslut
i need code:var v_name = null;$.ajax({ type: "GET", url: "Testpage.aspx", data: "name=test", dataType: "html", success: function(mydata) { v_name= mydata;}});alert(v_name);
Oraclee
@oraclee: Why? It doesn't make sense.
RoToRa
@oraclee, I don't (and I dont think I'm alone here) understand you. If you want to show an alert with the value of mydata once the ajax call completes, then thats what you need to do. Your code will not work, because as others have mentioned $.ajax is asynchronous. In your code, alert(v_name) will be called BEFORE the ajax call has completed, and thus v_name is not set when you show the alert box. This is why its null.
Mailslut
A: 

In addition to the other answers, also keep in mind that by default .ajax GET requests are cached, so depending on your browser, it may look like all of your requests are returning the same response. Workarounds include (but are not limited to): using POST instead of GET, adding a random querystring to your url for each request, or adding 'cache: false' to either your ajax call or to the global ajaxSetup.

James H