Reputation: 1304
I've a jquery post function that returns a data object from a php code block.
$.post("get_chat_history.php", {
item_id : item_id,
participant_1 : participant_1,
participant_2 : participant_2
}, function(data) {
alert(data);
return data;
});
this is called from the following function in another javascript file
var data = getChatHistory(current_member_id,item_global["user"] ["member_id"],item_global["id"]);
alert(data);
now inside the $.post the alert(data) throws out the correct values in json format, but when I test the same value returned to the calling function I get undefined.
Is there something I'm missing as I want to keep this function generic and callable from elsewhere??
Regards,
Sapatos
Upvotes: 0
Views: 580
Reputation: 1719
The problem you are facing is that jQuery.post is asynchronous. When getChatHistory is being called it has not yet received a reply from the server so it is undefined
.
For this to work I would implement getChatHistory
as a function that takes the data you need to pass to the server, and a function to perform when the 'success' part is triggered.
Upvotes: 0
Reputation: 7596
That's because this function runs asyncronim and returns data to anonymous function function(data) {}
. Use callbacks.
Here is example:
function getFoo(callback){
$.get('somepage.html', function(data){
callback(data)
})
}
getFoo(function (data){
// do something with data
})
Upvotes: 1