How to get data from jQuery.post()?
Question by Alwayz Change
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
Answer by Nishant
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);
Answer by Starx
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.