Hello I have the following jquery function
(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 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 does show the response bn:
I understand that you have the value of the response when printing the console log, but not when returning the response variable.
This is because ajax is asynchronous and at return time your ajax function hasn't resolved yet.
To capture the response of an ajax I suggest that within your Success function, after getting a response you introduce your validation function, Eg:
As an alternative suggestion (and what I consider to be bad practice), you can wrap the value of your response in an HTML element and then take from there.
EG:
Then query the value
There is a third alternative: you can use the async:false property, which stops code execution until your ajax responds.
I hope it helps you, Greetings.