Alwayz Change
Alwayz Change

Reputation: 225

How to get data from jQuery.post()?

My problem is that i wanna use post data outside it's function, example:

$(function() {
  var s = 'something ';
  $.post('ajax.php', {option: 'test'}, function(data) {
    s += data; // data: 'hello world';
  });
  alert(s); // output: 'something ';
});

my expected result is 'something hello world'. how can i deal with this?
Thanks

Upvotes: 1

Views: 267

Answers (6)

Tomm
Tomm

Reputation: 2142

Shouldn't that be:

   $(function() {
       var s = 'something ';
       $.post('ajax.php', {option: 'test'}, function(data) {
         s += data; // data: 'hello world';
        alert(s); // output: 'something ';
       });
    });

Obviously, the data will be available in s only after the ajax call has been completed (as Alex pointed out), but after that it will be persistent...

Upvotes: 4

Kanishka Panamaldeniya
Kanishka Panamaldeniya

Reputation: 17566

var s = 'something ';

$.ajax({
      url: 'ajax.php',
      type: "POST",
      data: ({option: 'test'}),
      async:false,
      success: function(data){
         s += data;
      }
   }
);

 alert(s);

you need to synchronize the request by async:false,

Upvotes: 3

Starx
Starx

Reputation: 78971

You code should be working. Unless the ajax.php is not echoing "Hello World" at the end. Please make sure of it and try to post the results. Errors or output, whatever you can feed us.

Upvotes: 0

Nishant
Nishant

Reputation: 55856

Use $.ajax with async:false, I assume the data is coming as content-type:json/application e.g.

var s = 'something ';
$.ajax({
      url: "ajax.php",
      type: "POST",
      data: ({option: 'test'}),
      dataType: "json",
      async:false,
      success: function(msg){
         s += msg.data;//msg={data: "hello world"}
      }
   }
);
alert(s);

Upvotes: 2

FiveTools
FiveTools

Reputation: 6030

You could write the data to any number of html elements and have it available outside of the function. You could use a global variable. You could store in session. Many answers here. Do I understand your question?

Upvotes: 0

alex
alex

Reputation: 490143

You have a syntax error; there should be a ) at the end of the post() callback.

In addition, when that alert() is called, the XHR has not finished yet and assigned the new info to that variable. You would need to place it in the callback of post().

Upvotes: 1

Related Questions