0

Possible Duplicate:
return from a function ajax
JavaScript asynchronous return value / assignment with jQuery

How do you output the data variable to the second alert statement.

        $.post("index.ajax.php", { lookup:value }, 
        function(data) {
            alert(data)
            test = data;
        })
        alert(test)

Or would it be possible to do something like this?

function confirm_search(input) {
    $.post("index.ajax.php", { lookup:input }, 
    function(data) {
        $("#temp").val(data);
    })
}

var test = confirm_search(value);
alert(test); 
Community
  • 1
  • 1
hawx
  • 1,629
  • 5
  • 21
  • 37

3 Answers3

3

You can't.

AJAX is asynchronous. The response is not available until some time later.

The jQuery.post call will begin the AJAX request, and return the jqXHR object which is handling the request. The script will continue to be executed (alert(test) will fire next), and then some time later when the AJAX request has completed (i.e. the HTTP response is received), the callback:

function(data) {
    alert(data)
    test = data;
}

will be executed.

Matt
  • 74,352
  • 26
  • 153
  • 180
0

Try this way :

var test;
$.post("index.ajax.php", { lookup:value }, 
    function(data) {
       alert(data)
       test = data;
})

function alertTest(){
  if(test != undefined) {   
    alert(test);
    clearInterval(t);
  }
}  

var t = setInterval(alertTest, 1000);

You will get test value when ajax request is completed and test is assigned

hungryMind
  • 6,931
  • 4
  • 29
  • 45
0

If you are strict with scenerio, define test variable in global scope, in that way you can use it anywhere in your code.

Riz
  • 9,703
  • 8
  • 38
  • 54