0

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

3
  • 1
    Ajax is asynchronous (the A means asynchronous). Why do you think you have to provide a callback? If you could simply return a value, then $.post could return that value directly and you would not need a callback. Commented Aug 13, 2012 at 11:26
  • 1
    possible duplicate of Javascript Function With JQuery POST Always Returns undefined Commented Aug 13, 2012 at 11:26
  • Check out the related questions. There are several similar questions which should prove helpful. Commented Aug 13, 2012 at 11:26

2 Answers 2

1

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
})​
Sign up to request clarification or add additional context in comments.

1 Comment

Or shorter: $.get('somepage.html', callback).
0

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.

For more on callbacks.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.