I have a registration form and am using $.ajax
to submit it.
This is my AJAX request:
$(document).ready(function() {
$("form#regist").submit(function() {
var str = $("#regist").serialize();
$.ajax({
type: 'POST',
url: 'submit1.php',
data: $("#regist").serialize(),
dataType: 'json',
success: function() {
$("#loading").append("<h2>you are here</h2>");
}
});
return false;
});
});
In my submit1.php file I check for the existence of fields email address and username in the database. I wish to display an error message if those value exist without a page refresh.
How can I add this to the success callback of my AJAX request?
Make sure you're not printing (echo or print) any text/data prior to generate your JSON formated data in your PHP file. That could explain that you get a -sucessfull 200 OK- but your sucess event still fails in your javascript. You can verify what your script is receiving by checking the section "Network - Answer" in firebug for the POST submit1.php.
Add 'error' callback (just like 'success') this way:
So, in my case I saw in console:
The result is probably not in JSON format, so when jQuery tries to parse it as such, it fails. You can catch the error with
error:
callback function.You don't seem to need JSON in that function anyways, so you can also take out the
dataType: 'json'
row.The success callback takes two arguments:
Also make sure that the
submit1.php
sets the proper content-type header:application/json
I was returning valid JSON, getting a response of 200 in my "complete" callback, and could see it in the chrome network console... BUT I hadn't specified
once I did, unlike the "accepted answer", that actually fixed the problem.
in my case the error was this was in the server side and for that reason it was returning a html