0

I have a set of time out functions inside one function

function myFunction()
{
   var data;

   setTimeout(function(){
       $.ajax({
         //My Ajax Junk
         success: function(data) {
            var data = data.trim();
            // I want to be able to use this later on.
         }
       }):
   }, 6000);

   setTimeout(function(){
      var shipping = 'f_name='+f_name+data;
      // Append data from previous call to shipping
   }, 12000);
}

I'm wanting to retrieve the data from the ajax success function and then use it inside the next timeout function by appending it to the shipping variable. I have declared the variable data outside of all the functions and then tried to add the success data to it. When I alert out the shipping variable it doesn't show anything extra (what the data should be adding).

The data is returning because I can see it in Google Chromes Network Tab.

How can I set a variable to be used throughout the entire function!?!?!?!?

Thank you in advance.

Also, the success function is returning prior to the call for the data to be added because of the timeout functions. I played with them to be set right for this instance.

moevans
  • 79
  • 1
  • 2
  • 6
  • You should have a read of this question http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call – Musa Feb 14 '15 at 21:15

3 Answers3

0

As a bad way: up your var data; and change var data = data.trim(); to tdata = data.trim(); from the function:

var tdata;
function myFunction(){

    setTimeout(function(){
       $.ajax({
         //My Ajax Junk
         success: function(data) {
            tdata = data.trim();
            // I want to be able to use this later on.
         }
       }):
    }, 6000);

    setTimeout(function(){
        var shipping = 'f_name='+f_name+tdata;
        // Append data from previous call to shipping
       }, 12000);

}

RedBuld
  • 1
  • 2
  • You need to change the variable name. Data is used as the argument name of the success function. – Faris Feb 14 '15 at 21:04
0

Use another name for the global variable like global_data and in the ajax assign the data value using global_data = data.trim()

Alvaro Flaño Larrondo
  • 5,516
  • 2
  • 27
  • 46
  • I still need to wait 6 minutes before accepting answers although, this is the one I'm accepting. Once you think about it, it makes sense! Thank you for pointing it out. – moevans Feb 14 '15 at 21:06
0
function myFunction()
{
   var data;

   setTimeout(function(){
       $.ajax({
         //My Ajax Junk
         success: function(resp) {
            data = resp.trim(); // Dont declare it inside
            // I want to be able to use this later on.
         }
       }):
   }, 6000);

   setTimeout(function(){
      var shipping = 'f_name='+f_name+data;
      // Append data from previous call to shipping
   }, 12000);
}
void
  • 36,090
  • 8
  • 62
  • 107