Function to send AJAX data?

Asked

Viewed 58 times

2

I am 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 tried with the code above, changing the FormData line 2 that will be passed by parameter.

The return will certainly be a string, but when trying to catch the return I cannot:

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

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

What would be the mistake?

1 answer

3


The function $.ajax is asynchronous: her result is not available when she finishes running. You need to make your function (sendAjax) asynchronous as well, getting a function (callback) which 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
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.