4

Possible Duplicate:
return from jquery ajax call
jQuery: Return data after ajax call success

        $.ajax({
            url:"list.php",
            dataType: "json",
            success: function(resp){
                for(var i=0;i<resp.length;i++){
                    $('#goods_list').append(
                      "<h3>" + resp[i]["name"] + "</h3>"
                      +
                      "<div>Price: NT$" + resp[i]["price"] + "<br />"
                      +
                      resp[i]["description"]
                      +
                      "<hr /> <a href=# alt='"+ resp[i]["sn"]+ "' class='add_to_cart'>Add</a> | More"
                      +"</div>"
                    );
                }

                var resp2 = resp;
            }
        });

        $('body').append(resp2[0]["price"]);

And FireBug said:

ReferenceError: resp2 is not defined
$('body').append(resp2[0]["price"]);

How can I use $.ajax success data in somewhere else? (outside the $.ajax function)

The concept is similar to "Global Variables".

Community
  • 1
  • 1
Jean Y.C. Yang
  • 4,382
  • 4
  • 18
  • 27
  • You cannot because the request is asynchronous (unless you make it synchronous, which blocks your script). You have to move that line _into_ the success handler. – Michael Berkowski Jan 05 '13 at 14:24
  • I'm not exactly sure what pattern you're after, but you can also return the ajax call in a function, and then use `func().done(...)` anywhere. – pimvdb Jan 05 '13 at 15:05

1 Answers1

0

If you simply want to use the response content outside the success callback, you should declare your variable outside the method something like:

var resp2;
$.ajax({
    url:"list.php",
    dataType: "json",
    success: function(resp){

        for(var i=0;i<resp.length;i++){

            $('#goods_list').append(
            "<h3>" + resp[i]["name"] + "</h3>"
            +
            "<div>Price: NT$" + resp[i]["price"] + "<br />"
            +
            resp[i]["description"]
            +
            "<hr /> <a href=# alt='"+ resp[i]["sn"]+ "' class='add_to_cart'>Add</a> | More"
            +"</div>"
            );

        }

        var resp2 = resp;
    }
});

Anyway, you have to keep in mind that very probably, almost surely, the code after the $.ajax call will be executed before the success callback. It will happen because this is a async call. The browser will execute the $.ajax call, and wait for the response in a second thread, just after the request has been sent, the next statement (in your code, the .append call) will be executed.

So to acoomplish what you want, you should place the .append call within your success callback.

Adilson de Almeida Jr
  • 2,761
  • 21
  • 37