1

I'm trying to store a value I get with $.post() for use, but I'm running into an issue where the variable is being set before $.post() is being run. I don't get it. $.post() is encapsulated in a method for generic reuse. Javascript code below.

// call the post function
var zip_check = sendPost('{some url here}', new_zip);
console.log(zip_check);

/**
* sendPost
*
* Sends data via jQuery post and returns required result.
*
* @param  string target_url - where post is going
* @param  string post_data  - information to be sent
* @return string            - data to be manipulated
*/
function sendPost(target_url, post_data) {
   $.post(target_url, {
      post_data:post_data
   }).done(function(data) {
      console.log(data);
      return data;
   }).fail(function(e) {
      console.log('AJAX Failure: ' + e);
   });
}

As I said above, zip_check will store "undefined", print out to console, and then $.post() will run, but not return the value to zip_check. Does the the problem make sense?

2 Answers2

2

You are calling an asynchronous function..

A small modification of your function will solve it:

function sendPost(target_url, post_data, callback) {
    $.post(target_url, {
        post_data: post_data
    }).done(callback).fail(function (e) {
        console.log('AJAX Failure: ' + e);
    });
}

sendPost('http://jsfiddle.net/echo/jsonp/ ', {
    data: 'send'
}, function (data) {
    console.log(data);
});
  • it does an AJAX request with given url and post data.
  • when it finishes, done() will be called, which will call callback inside itself.
Kai
  • 1,156
  • 8
  • 18
2

You need to use a callback function.

sendPost('test.php', {zipcode:12345}, checkZipcode);


function checkZipcode(new_zip)
{
  /** Do stuff with your zip code **/

  console.log(new_zip);
}


/**
* sendPost
*
* Sends data via jQuery post and returns required result.
*
* @param  string target_url - where post is going
* @param  string post_data  - information to be sent
* @param  function callback - function called after POST response
*/
function sendPost(target_url, post_data, callback) {
   $.post(target_url, {
      post_data:post_data
   }).done(function(data) {
      console.log(data);

      callback(data);

   }).fail(function(e) {
      console.log('AJAX Failure: ' + e);
   });
}
chavakane
  • 245
  • 1
  • 6