Return the answer from an ajax [duplicate]

0

Hi, I have the following function of jquery

  (function ($) { 
$.onlyData = function (id) {
        var respuesta;
        var datos =$(id).data("sql");
        datos=datos.split("-")
        var campoBD = datos[0];
        var tableModel = datos[1];
        var arr = $(id).val();
        var parametros = {
            "Field": {
                "Data": arr
            }
        };
        $.ajax({
            data: parametros,
            url: '/Desarrollo/consultar_existencia/' + campoBD + "/" + tableModel,
            type: 'post',
            dataType: "json",
            success: function (response) {
                console.log(response);
                respuesta=(response);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.log(jqXHR);
            }
        });

        return "chap"+respuesta;
    }
})(jQuery);

And when I click on a button

enter here:

var unico = 0;
        alert($.onlyData("#" + $(".txtEmail").attr("id")));

but the alert arrives like this:

and I need the ajax response for a validation and the thing is that the console if it shows bn the response:

    
asked by Andrés Vélez 20.06.2018 в 17:35
source

1 answer

0

I understand that you have the value of the response at the moment of printing the console log, but not at the moment of returning the response variable.

This is because ajax is asynchronous and at the time of doing the return your ajax function has not yet been resolved.

To capture the response of an ajax, I suggest that within your Success function, after getting an answer, enter your validation function, eg:

success: function (response) {
    console.log(response);
    respuesta=(response);
    runMyValidations(response);
},

As an alternative suggestion (and that I consider bad practice), you can accommodate the value of your response in an HTML element and then take it from there.

EJ:

success: function (response) {
    $('#responseValue').html(response);
},

Afterwards, check the value

var myResponse = $('#responseValue').html();

There is a third alternative: you can use the async: false property, which stops the execution of the code until your ajax responds.

I hope it serves you, Greetings.

    
answered by 20.06.2018 / 18:14
source