Vahan
Vahan

Reputation: 534

Jquery post call back not works

Hi my jQuery callback function does not work.

 Competitor = {
    addCompetitorForSave: function($data) {

            $.post('/competition/add', $data , function($json) {

            }, 'json');

           return $json; // I need to return json data .
        }
}

after this I need to do next .

 var data  = $('someForm').serialize();
 var $json  = Competition.addCompetitorForSave(data);

Thanks a lot.

Upvotes: 0

Views: 112

Answers (3)

JaredPar
JaredPar

Reputation: 755557

The post completes asynchronously but the alert runs synchronously. Hence the qa value hasn't been set yet. Instead of return a value here you need to pass an additional callback into addCompetitorForSave.

addCompetitorForSave: function($data, callback) {
  var qa  = 0;
  $.post('/competition/add', $data , function($json) {
    callback($json);
  }, 'json');
}

var obj = ...;
obj.addCompetitorForSave(theData, function(qa) {
  alert(qa);
});

Upvotes: 3

Kevin Bowersox
Kevin Bowersox

Reputation: 94499

try:

addCompetitorForSave: function($data) {

        var qa  = 0;


        $.post('/competition/add', $data , function($json) {
             qa = $json; //this does not work
             alert(qa); //getting 0;
        }, 'json');

        return qa;
    }

Upvotes: 0

Supr
Supr

Reputation: 19042

The alert is called before the post has had a chance to complete. Put the alert inside the callback.

Upvotes: 3

Related Questions