I am currently learning asp.net core 3 and I can’t find any help regarding this issue that I have. I have a form that submits a value with a POST request. But I want the same button to have a GET request that populates another field with a .ajax / xmlhttprequest. But I want the POST method to be executed first and then the GET method. Is it possible to do it? I’ve tried doing it but I got stuck.
These are the methods inside my controller.
[HttpGet] public async Task<IActionResult> GetConvertedAmount() { var rate = await _db.ExchangeRates.Where(x => x.Name.Equals(_tM.Currency)).ToListAsync(); _tM.convertToCurrency(rate[0].Rate); var amount = _tM.Amount; return Json(amount); } [HttpPost] public ActionResult CalculateExchangeRatio(int amount_give, string type_to_give) { _tM.Amount = amount_give; _tM.Currency = type_to_give; return Ok(); }
And this is my JS script
$('#calculateButton').on("click", function () { $.ajax({ url: "/trade/getconvertedamount", type: "get", success: function (amount) { console.log(amount); alert(amount); } }); })
Advertisement
Answer
You can use the $.ajax ‘done’ chaining to complete the entire process:
$('#calculateButton').on("click", function () { $.ajax({ url: "/trade/calculateexchangeratio", data: { amount_give: 9.99, type_to_give: 'blahblah' }, type: "post" }) .done(function(){ $.ajax({ url: "/trade/getconvertedamount", type: "get" }) .done(function (amount) { console.log(amount); alert(amount); }); }); })