I am unable to use most jQuery in Ajax success. I am trying to have an error message from the response appear in my notify (toast) div, but anything I try except .show()
and .hide()
will not work.
I have used console.log()
to ensure it is definitely decoding the response from the url and everything is as it should, however I am unable to call functions inside the Ajax success function
This is my current JS which triggers at the click of a button.
function errMsg(code, msg) {
const eCode = '<b>E-NS: ' + code + ' </b> </br>' + msg;
const eMsg = '<span class="err" style="color: red;">' + eCode + '</span>';
$('.notify').empty().html(eMsg);
}
$(document).ready(function() {
$('#next-1').click(function(e) {
e.preventDefault();
$.ajax({
url:'../data.php',
method: 'POST',
data: $('#form-1').serializeArray(),
dataType: 'JSON',
success:function(response){
if(response.status === true){
$('#form-1').hide();
$('#form-2').show();
} else {
console.log(response.status);
console.log('Response = ' + response.code + response.error);
errMsg(response.code, response.error);
var eCode = '<b>E-NS: ' + response.code + ' </b> </br>' + response.error;
var eMsg = '<span class="err>' + eCode + '</span>';
$('.notify').empty().html(eMsg);
}
}
})
})
)}
It should be noted that there are no errors or warnings in the php or the jQuery appearing. I am new to AJAX, so I’m not entirely sure if this is something I am able to do, although it seems logical enough, no?
2
Answers
I was hiding my toast div (
$('.notify')
) until there was text inside the div. However, I neglected to add my function that showed this -- Which can be seen below -- and did not call it after updating the toast in the AJAXsuccess
function witherrorCheck()
When sending data as
JSON
the jQuery method.ajax()
expects an object in thedata
property of the object that is passed as the only argument. YourjQuery.serialize()
function creates an argument string for a URL. This will not work here. You should instead usejQuery.serializeArray()
:You should also check what the server will send back. In the case of my dummy JSON API there was not
.status
property being sent back. So it did not make sense to test for it.