-1

I have the usual callback method when doing AJAX calls. However, I have a situation where I need to store the success data from the callback to a variable, but when I try and retrieve the data it comes up null. Can anyone share some light into where I'm going wrong? Thanks in advance!

function getData(url, callback){
    $.ajax({
        type: 'GET', 
        url: url,
        success: callback 
    });    
};

var storeThedata = (function(){
    function theData(){
        var newdata = null;

        getData('someurl.json', function(data){
           newdata = data; // newdata now isn't null woo!
        });

        return newdata;
    }
    return { 
        getTheData: theData
    }
})();

var stored = storeThedata.getTheData();
console.log(stored); // Shouldn't be null
jms
  • 49
  • 1
  • 8
  • 3
    possible duplicate of [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – Deepak Ingole Mar 19 '14 at 04:29
  • @Pilot it's not necessarily a duplicate because I do the pattern described when it comes to using a callback and then using THAT function again in another function. If you'd read my code you'd see that it's trying to achieve something different. – jms Mar 19 '14 at 04:38
  • @ Jessi You are returning the newdata outside callback function and as Asych behavior it could be null – Deepak Ingole Mar 19 '14 at 04:46
  • @JessicaSilva - this is a pure duplicate. You've tried to fix the problem by just making one more level of async functions which doesn't help at all. It's real simple. You can't return data from a function that gets the data from an async function. You can ONLY use the data in the callback where the data arrives or call some other function from that callback and pass the data to it. You CAN'T return the data from the original function because it doesn't yet exist when that function returns. – jfriend00 Mar 19 '14 at 04:57
  • Ajax functions return sometime in the FUTURE. You can't use the data until they return. You can't know when they've returned except in the success handler for that ajax call. That's where you use the data. You have to learn how to write async code. – jfriend00 Mar 19 '14 at 05:08
  • @ Jessi please look at the ans posted below – Deepak Ingole Mar 19 '14 at 10:17

1 Answers1

0

Why not use Ajax response call,May be you want something like this.

$(document).ready( function(){
  $.ajax({
        type : 'POST',
        url : 'copycon.php',
        success : function(data){
    if(data=='saved')
    {
     alert("saved");
 console.log(data);
     
    }
    else
    alert("not save");
    console.log(data);
        },
        error : function(XMLHttpRequest, textStatus, errorThrown) 
        {alert ("Error Occured");}
                 });


});
Abhishek
  • 517
  • 3
  • 18