简体   繁体   中英

Using JSON data retrieved via AJAX in separate function

Apologies if this is a duplicate question, I've followed some steps from another question which didn't seem to help me. I am trying to retrieve some JSON data, store part of the data into a variable and use that variable in a separate function outside of the AJAX request.

My expected response from the json data is http://localhost:8000/tutorials/retrieve/?page=2 (This response shows if I log the variable inside of the AJAX code) however the actual response I get when I try to log the variable from another function is as follows:

n.Event {originalEvent: MouseEvent, type: "click", timeStamp: 1436727171161, jQuery21304066238570958376: true, toElement: div#loadmore.recentTutorials…}

Here is the current code

 var recentFirstPage = '';

function retrieveTutorials(){
  $.ajax({
    type: "GET",
    url: "/tutorials/retrieve",
    dataType: "json",
    success: function(data){
     **some unrelated parsing code here**
      //Set the variable to what I need
      recentFirstPage = data.next_page_url;
    },
    error: function() {
        alert("An error occurred processing AJAX request.");
    }
});
}

$('#main-content-wrap').on('click', '.recentTutorials', function(recentFirstPage){

        //Does not return expected result
        console.log(recentFirstPage);  
 });

When I click .recentTutorials I expect the console to log the data from JSON however it doesn't. Can someone help clear up my error(s)?

The reason that it doesn't log the data from JSON s that the call is asynchronous. This means that the function will execute top to bottom without waiting for the call to finish.

One method that's used is to leverage deferred objects which return a promise on completion. You can accept an anonymous function to the invoker function so that it's call back is executed within the scope of the click.

Observe:

function retrieveTutorials(){
    return $.ajax({
        type: "GET",
        url: "/tutorials/retrieve",
        dataType: "json"
    });
}

$('#main-content-wrap').on('click', '.recentTutorials', function(){

     //store our function call as an ajax promise
     var promise = retrieveTutorials();

     //wait for the ajax to return so we can mutate the data
     promise.done(function(data){
         //now our data will be properly
         recentFirstPage = data.next_page_url;
     });

});

The parameter in your click handler is the last and final nail in your coffin. It's always the jquery event and you shouldn't handle it at all.

You do need to call the retrieveTutorials() function within the handler and you need to pass it a callback function that will be executed on success. So your retrieveTutorials() function will look something like this:

function retrieveTutorials(success){
     $.ajax({ type: "GET", url: "/tutorials/retrieve", 
        dataType: "json", 
        success: success, 
        error: function() { alert("An error occurred processing AJAX request.");
 } }); }

And your click handler:

$('#main-content-wrap').on('click', '.recentTutorials', function(){
    retrieveTutorials(function(data){
        console.log(data.next_page_url);

    });

 });

You can also use all the promise based goodness in the other anwers, but the above would be an idiom you'll see again and again.

It seems to me that you are trying to log the data before the ajax is completed. It`s better to use deferreds . Try this:

function retrieveTutorials(){
  return $.ajax({ // will return deferred object
    type: "GET",
    url: "/tutorials/retrieve",
    dataType: "json",
    success: function(data){
     **some unrelated parsing code here**
      //Set the variable to what I need
      recentFirstPage = data.next_page_url;
    },
    error: function() {
        alert("An error occurred processing AJAX request.");
    }
});
}

$.when( retrieveTutorials() ).done(function ( data ) {
    console.log(recentFirstPage);  
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM