0

I need to store the data returned from a jquery $.post call in a variable called result. the code below works except on the first click result comes back as undefined... on the second click it returns the data from the php file as expected. Thanks.

$('a').on('click',function(){
  var cv = $(this).data('cv');
  var url= '_php/myphp.php';
  $.post(url,{contentVar:cv},function(data)
  {
    result = data
    return result;    
    });
    alert(result);
});
BryanK
  • 1,211
  • 4
  • 15
  • 33
  • You can just replace the word `data` in the callback to `result` rather than assigning it after the fact. – DevlshOne Aug 11 '13 at 14:19
  • 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) – Arun P Johny Aug 11 '13 at 14:20
  • you can't return data from a asynchronous call like that... there is probably a 1000 question with the same topic... the solution is to use a callback function to process the value returned by ajax as mentioned each of those questions – Arun P Johny Aug 11 '13 at 14:20

3 Answers3

1

You should use result as global variable.

Global variable will let you use the variable outside the scope:

var result;
$(function(){
    $('a').on('click',function(){
      var cv = $(this).data('cv');
        var url= '/echo/json/';
      $.post(url,{contentVar:cv},function(data)
      {
        result = data;
        //you don't need any return, its callback function 
      }).done(function(){
          alert(result);
      });

    });
});

You can find more information on: http://snook.ca/archives/javascript/global_variable

Idan Gozlan
  • 3,173
  • 3
  • 30
  • 47
1

By using the .done() method, you are waiting for the AJAX call to get a successful response before alerting the result.

$('a').on('click',function(){
  var cv = $(this).data('cv');
  var url= '_php/myphp.php';
  $.post(url,{contentVar:cv},function(data) {
    result = data;
    return result;    
  }).done(function() {
      alert(result);
  });
});
DevlshOne
  • 8,357
  • 1
  • 29
  • 37
0

Try it like,

var result=null;// initially initialize this variable
$('a').on('click',function(e){
   e.preventDefault();// use this line to prevent its default behaviour
   var cv = $(this).data('cv');
   var url= '_php/myphp.php';
   $.post(url,{contentVar:cv},function(data)
   {
      result = data;
      alert(result);// first alert
      return result;    
   });
   alert(result);// its global now, check this too
});

If this not fixes then use $.ajax() with async:false option. Call your Ajax code synchronously so that the result variable initialized and you get the result after your Ajax call.

Rohan Kumar
  • 40,431
  • 11
  • 76
  • 106