Hello, I would like you to help me with something I am doing, I have read but I have not understood something because I do not make it work, I put them in context:
I need to call a % of a table and since it is running I want to do a get in the controller I have this:
public async Task<JsonResult> GetTaxPercen(int id)
{
try
{
impuesto Item = await _iImp.ObtenerPorId(id);
return Json(Item);
}
catch(Exception e)
{
return Json(e.Message);
}
}
Incidentally, "Item" has 5 records and has data. I try to call this function with an Ajax in Jquery:
function getImpuesto(id) {
var iUrl = "/Mov/GetTaxPercen?id=" + id;
$.ajax({
url: iUrl,
type: 'GET',
data: '{}',
dataType: 'json',
contentType: "application/json; charset=utf-8",
asyn: true,
success: function (result) {
if (result != null) {
return result.porcentaje;
}
},
error: function () {
return result.responseText;
}
});
};
This is called from another jquery function:
$("#neto").on("change keyup paste", function () {
if ($.isNumeric($("#neto").val())) {
var pimp = self.getImpuesto(3);
if (pimp > 0) {
pimp = pimp / 100;
if ($("#neto").val() > 0) {
$("#iva").val(parseFloat($("#neto").val() * pimp).toFixed(2));
$("#monto").val(parseFloat(parseFloat($("#neto").val()) + parseFloat($("#iva").val())).toFixed(2));
}
}
}
else { DesplegarModal('Advertencia Error', 'Necesita ingresar un valor númerico valido'); }
});
The problem is that the ajax does return the value but I don't know how to handle the asynchrony in jqueryu and it returns me undefined, how can I make it wait to assign the values?
Thank you if you have any example to read I would appreciate it
first you have to understand that an asynchronous method runs in the background, that is, it is not sequential and does not wait for it to finish, these requests were born to prevent the pages from sticking while waiting for a slow process and to avoid having to reload the page, I invite you to read more about asynchronous methods. Taking into account the above, your problem is when you use return in the ajax method , since the method returns you immediately even if the request had not finished.
What you have to do is move your code you can create a method that is executed when the request ends, then the flow would be like this: you invoke your ajax request (it is done in the background) let's suppose that it takes 30 seconds, after 30 seconds that it responds will get to the success method here you invoke your new method to display the percentage.
It would be something like this:
Here you would invoke the asynchronous method:
ajax method.
Method to display the value