Function to send given AJAX?

2

I'm trying to set up a function to send an ajax, the function should return my ajax result:

var url = localStorage.getItem("site");
var dataForm = new FormData(this);
$.ajax(
{
    type: "POST",
    url: url ,
    data: dataForm ,
    contentType: false,
    cache: false,
    processData:false,
    success: function(result)
    {
        if(result == null || result.length < 3 || result == "ok" || result == " ")
        {
            return "ok";
        }
        else
        {
            return result;
        }
    },
    error: function(xhr, status, error)
    {
        return error;
    }
});

I've tried the code above, changing the FormData of line 2 that will be passed by parameter.

The return will certainly be a string, but when I try to get the return I can not:

var return = sendAjax (this). // where this is my form

retorno is always undefined . I have already made sure that ajax has a return on function success

What would be the error?

    
asked by anonymous 22.04.2016 / 00:34

1 answer

3

The $.ajax function is asynchronous: its result is not available when it finishes executing. You need to do your asynchronous sendAjax function too, getting a callback function that will be called when the result is available. Something similar to the code below:

function sendAjax(dataForm, callback) {
    var url = localStorage.getItem("site");
    $.ajax(
    {
        type: "POST",
        url: url ,
        data: dataForm ,
        contentType: false,
        cache: false,
        processData:false,
        success: function(result)
        {
            if(result == null || result.length < 3 || result == "ok" || result == " ")
            {
                callback("ok");
            }
            else
            {
                callback(result);
            }
        },
        error: function(xhr, status, error)
        {
            callback(error);
        }
    });
}

sendAjax(new FormData(this), function(retorno) {
    // Use o valor de 'retorno' aqui
});
    
22.04.2016 / 00:48