0

i have this ajax call function.

function saveData(ip)
{

    $JQ.ajax({

     type: "POST",

     url: "all_actions.php",

     data: 
     {
         page_url:document.URL,
         ip_address:ip 
     },

     success: function(responce)
     {

         if(responce)
         {
             var newtoken;
             newtoken=responce;
             return newtoken;
         }
     }
    });
}

Then i have another function

 function getToken()
{
    var ip=myip
    var mytoken;
    mytoken=saveData(ip);
    alert(mytoken);

}

My token giving undefined in alert.Although if i alert newtoken variable in savedata response it gives correct value in alert box.why if i return that avlue it does not assigned to mytoken.

is it something time delay issue.??

Need your help...

1
  • 1
    AJAX = Asynchronous Javascript And XML. There are many questions with the same problem here on SO :) Commented Jan 23, 2013 at 11:25

3 Answers 3

1

You cannot return from an asynchronous call.

You have to consume the return data inside the success function. Whatever you are going to do with token, write that code inside the success handler.

success: function(responce)
 {

     if(responce)
     {
         var newtoken;
         newtoken=responce;

         // Global variable
         sourceid = newtoken;

         return newtoken; // This won't work
     }
 }

Also

 function getToken()
{
    var ip=myip
    var mytoken;
    mytoken=saveData(ip); // This won't return any data
    alert(mytoken); // This won't give you anything useful

}
Sign up to request clarification or add additional context in comments.

2 Comments

I have to assigned that value below the page to another javascript variable.thats why i want to return this..like this sourceid = getToken();
Then you will have to assign sourceid = newtoken; inside the success handler. Note that sourceid should be global.
1

Hi friends This is solution that for i was looking.

    function saveData(ip)
{

    return $JQ.ajax({

     type: "POST",

     url: "all_actions.php",

     data: 
     {
         page_url:document.URL,
         ip_address:ip 
     },
     async: false,

    }).responseText;
}
function getToken()
{
    var ip=myip
    var mytoken;
    mytoken=saveData(ip);
    return mytoken;
}

Comments

0

The first 'A' in AJAX is 'Asynchronous'. Your alert is running before the AJAX request has had a chance to complete. You need to handle whatever you wish to do with the response inside of the success: function() or .done() functions of jQuery:

success: function(responce)
{
    if(responce)
    {
        var newtoken = responce;

        // Work here with newtoken...
    }
 }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.