-2

I have this $.post statement, I wanted to get the function outside the $.post data.

$(function(){
   var new_data = '';
   $.post('my_url', {}, function(data){
       new_data = data;
   });

   console.log(new_data);
});

This is what I did, but it does not give an output, the data im getting is a json_encoded data from PHP how can I get the data outside of the $.post statement?

Erik Philips
  • 53,428
  • 11
  • 128
  • 150

1 Answers1

0

Whether you extrapolate out the logging or not, it will still need to be in the callback of the .post.

You'll need to either put your logging directly inside the callback of the .post:

$(function() {
  var new_data = '';
  $.post('my_url', {}, function(data) {
    new_data = data;
    console.log(new_data);
  });
});

Or make the callback reference an external function:

$(function() {
  var new_data = '';
  $.post('my_url', {}, function(data) {
    new_data = data;
    response(new_data);
  });
});

function response(new_data) {
  console.log(new_data);
}
Obsidian Age
  • 41,205
  • 10
  • 48
  • 71