0

I have designed a website that takes a users input as search parameters and uses them to search a database using an AJAX call to a PHP page. In this AJAX call, I obviously have some data (formatted as a JSON file) that I manipulate and use in the "success" section of the ajax arguments. Here's the problem--I want to be able to analyze the data from the narrowed search the user puts in against the data from the entire database population. How can I do this? I thought I would just do another AJAX call, but the data from that call seems inaccessible from the outside, and I can't find any ways to "export" it outside the call. Here is a shortened version of the code:

$.ajax({
    url: URL for the search .php,
    cache: false,
    data: {
            Various search parameters by the user
        },
    dataType:"json",
    success:function(data){
       Data manipulation and reading the resulting JSON
       $.ajax({
            url:URL2 for the population .php,
            cache: false,
            dataType:"json",
            success:function(data){
                population data stuff here
            },
            error: error stuff


    }
        error: error stuff
}

That's the only way I know to access the database thus far. How can I somehow pull the data out of that second AJAX so that I can use it in the first one?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
superspartan999
  • 191
  • 4
  • 14
  • Possible duplicate. You want to chain ajax calls, see this question: http://stackoverflow.com/questions/995529/how-to-chain-ajax-requests – MStodd Jul 26 '12 at 19:47

1 Answers1

1

Since your working with asynchronous callbacks you can't "extract" the data from the second call and use it in the first. What you will have to do is make the two calls and use the data from each within the second calls success callback. You can do this if rename the variables you're using with the success callback functions to be unique.

$.ajax({
    url: /**/,
    success:function(response1){
       $.ajax({
            url: /**/,
            success:function(response2){
                /* use both response1 and response2 here */
            },
            error: /**/
       })
    },
    error: /**/
})

If you aren't using data from the first ajax call to make the second ajax call you can use something like jQuery.when to wait for both request to finish.

travis
  • 8,055
  • 1
  • 17
  • 19