Daniel
Daniel

Reputation: 37

Getting Success Results from $.post

I'm having a hard time figuring out how to get the success results from jquery/ajax. I've tried to call an outside function to make sure.. setting the result as global is.. global? I get how scope works, but it doesn't seem to work here. So maybe I don't understand scope regarding jquery? The following is where I'm at now - lots of trial and error. In this case, using an alert on data['test'] gives me the result I'm looking for, but when I call setSession() setting session_results does not work.

*edit - I just noticed that the script doesn't wait for $.post to finish, so there's my problem. Callback functions, according to other questions asked around here. Anyone have an example or recommendation? Otherwise, this thread can be closed.

**edit - Thanks Cuong Le.

// SESSION
var session_results;
function setSession(data) {
    session_results = data;
}
function SESSION() {
    $.post(
        "handler.php",
        { get_session: "get_session" },
        function(data) {
            alert(data['test']);
            setSession(data);
        },
        "json"
    );
}

SESSION();
alert(session_results['test']);

Upvotes: 1

Views: 51

Answers (2)

cuongle
cuongle

Reputation: 75326

You should wait until the ajax post is done then you are able to alert alert(session_results); correctly, use promise concept in jquery:

var session_results;
function setSession(data) {
    session_results = data;
}

function SESSION() {
    var promise = $.post(
        "handler.php",
        { get_session: "get_session" },
        function(data) {
            alert(data['test']);
            setSession(data);
        },
        "json"
    );

    return promise;
}

var result = SESSION();

result.done(function(){
    alert(session_results);
});

For more corrective, you should use the new syntax of jquery ajax by using done function:

function SESSION() {
    var promise = $.post( "handler.php",  { get_session: "get_session" })
                    .done(function(data) {
                        alert(data['test']);
                        setSession(data);
                    });

    return promise;
}

Upvotes: 1

Shahar
Shahar

Reputation: 1677

This is because AJAX stands for Asynchronous JavaScript and XML. It isn't guaranteed to be finished by your next call. So what you can do instead is:

var session_results;
function setSession(data) {
    session_results = data;
}
function SESSION() {
    $.post(
        "handler.php",
        { get_session: "get_session" },
        function(data) {
            alert(data['test']);
            setSession(data);
            alert(session_results['test']); //moved to here
        },
        "json"
    );
}

SESSION();

Or you can use $.ajax with async off.

Upvotes: 0

Related Questions