Unable to call function on AJAX success
P粉020556231
2023-09-02 13:54:42
<p>I cannot successfully use most jQuery with Ajax. I'm trying to get the error message from the response to appear in my notification (toast) div, but in addition to <code>.show()</code> and <code>.hide()</code> Nothing I try will work. </p>
<p>I've used <code>console.log()</code> to make sure it does decode the response from the url and everything works as expected, but I can't call the function inside the Ajax success function< ;/ p>
<p>This is my current JS that fires on button click. </p>
<pre class="brush:php;toolbar:false;">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);
}
}
})
})
)}</pre>
<p>It is important to note that there are no errors or warnings in php or jQuery. I'm new to AJAX so I'm not entirely sure if this is something I'd be able to do, although it seems logical enough, no? </p>
When sending data as
JSON
, the jQuery method.ajax()
requires passing in an object-unique argument in the object'sdata
property. YourjQuery.serialize()
function creates the parameter string for the URL. This won't work here. You should usejQuery.serializeArray()
:You should also check what the server will send back. For my dummy JSON API, the
.status
property is not sent back. So there is no point in testing it.I hide my toast div (
$('.notify')
) until there is text in the div. However, I neglected to add a function that displays this (shown below) and did not call it after updating the toast in the AJAXsuccess 更新 AJAX
function using
errorCheck() Code>