Pregunta

function form(elem) {
    var dati = $(elem).serialize();
    var action = $(elem).attr("action");
    var result = "";
    $.post(action, dati, function (data) {
        result = jQuery.parseJSON(data);
        alert(result)
        return result;
    });
}
$(document).on("submit", "#new-search-field", function () {
    var data = form($(this));
    alert(data);
    if (......) {.....
    }
});

I need to read the asynchronous result from post request but i can't because i get alert(data) before "return result;"

How can i solve it?

¿Fue útil?

Solución 2

You need to include a callback for your post, since with they way your code is now, it calls the post, but then just continues to execute the next command. I would just add an extra parameter to your function. Something like this:

function form(elem, callback) {
    var dati = $(elem).serialize();
    var action = $(elem).attr("action");
    var result = "";
    $.post(action, dati, function (data) {
        result = jQuery.parseJSON(data);
        callback(result);
    });
}
$(document).on("submit", "#new-search-field", function () {
    form($(this), function (data) { alert(data); });
    if (......) {.....
    }
});

Hope this helps

Otros consejos

This is not how asynchronicity works.

You get the alert(data) before return result; because $.post works asynchronously. The form function executes and returns, and then some time later $.post will have the Ajax response data available and will call the provided callback function passing the data as an argument.

To accomplish what you want you basically have two options:

  • You can either use a callback (that will get called once the asynchronous action completes).
  • Use promises/deferreds.

Callback version 1:

function form(elem, callback) {
    ...
    $.post(..., function(data) {
        data = f(data); // transform data somehow if you have to
        callback(data);
    });
}
$(document).on(..., function() {
    form($(this), function(data) {
        // use data
    });
});

Callback version 2:

function form(elem, callback) {
    ...
    $.post(..., callback);
}
$(document).on(..., function() {
    form($(this), function(data) {
        // use data
    });
});

Promises version:

function form(elem) {
    ...
    return $.post(...);
}
$(document).on(..., function() {
    form($(this))
        .done(function(data) {
           // use data
        })
        .fail(function() {
           // error
        });
});

this is because your post is implemented asynchronous. try to use a callback function to access the result of your post request

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top