i want to get json response from server on button click and parse to div, but i stuck how to do it.
<button type="submit" id="btPay" name="btPay"> Go for Payment </button><br>
<div id="notif"></div>
My external js as follow:
var resJson;
async function myFunction() {
var settings = {
"url": "urlApi",
"method": "POST",
"timeout": 0,
"headers": {"headerContents"},
"data": JSON.stringify({"inputData"})
};
$.ajax(settings).done(function (response) {
resJson = $.parseJSON(response);
});
}
async function setResponse() {
$("#notif").html(resJson);
}
$('#btPay').bind('click', function() {
myFunction();
setResponse();
})
The problem is i cannot get Json response value. based my js, do i missed something?
Thanks and appreciate for help.
3
Answers
when try in postman with data:
The response I get like follow:
I think it is better to use await to get the answer to get the answer!
just like this:
I hope it helped you.
In your event handler for the button click you call the functions
myFunction()
andsetResponse()
directly one after the other. The second function will be called before the first will have received the results from the AJAX call. To make it work thesetResponse()
function needs to be called from within thedone()
callback function in your AJAX call inmyFunction()
:Another change I made is that I stopped using the global variable
respJson
. The JSON string is stored in a local variable of the same name and used as the first parameter in the function callsetResponse(respJson)
.Since the deferred jQuery function
$.ajax()
has not been called with theawait
keyword (but is resolved in adone()
callback instead) there is no need for the surrounding function to be an asynchronous one and theasync
keyword can be safely dropped.