I’m working on adding some Ajax to a web page that I have using jQuery. Note that I’m new to Ajax. The page is a simple registration form, and I want to check if the email address the user supplies is already registered, and tell the user if it is, before the form redirects to registration code.
I’ve been reading this question and its answers, and experimenting to reproduce the effect, but without success.
When I click on submit, the javascript function is called (I’ve proven this by adding some diagnostic code into the checkEmail() function), however when I check my Apache server logs, I can see all the requests that I’m expecting, except for the call to /user/process/chechemail.php. The code (below) is located in the /user/ directory, I’ve modified the url: path with all variations of relative and absolute paths. Nothing is recorded in the Apache error log.
When the user clicks the submit button, they see the message “Something went wrong!”. Can anyone spot what is wrong?
The code I have is as follows:
<script>
function checkEmail()
{
$.ajax(
{
type: "POST",
dataType: "html",
data:
{
email: $('#email').val()
},
url: "/user/process/checkemail.php"
})
.done(function(response)
{
$('#message').html(response);
})
.fail(function()
{
$('#message').html("Something went wrong!");
return false;
});
}
</script>
<div id="register-form">
<form name="register" action="process/register.php" method="post" onsubmit="return checkEmail();">
<div class="register-email-cell">
<p class="text">Email Address</p>
</div>
<div class="register-email-cell">
<input class="input" type="text" name="email">
</div>
<div class="register-email-cell">
<input class="button" type="submit" value="Register">
</div>
<div>
<p id="message" class="text"></p>
</div>
</form>
</div>
Notes:
- The
<script>reference to jQuery is in a PHP include, not shown above - /user/process/checkemail.php – looks for $_REQUEST[’email’], and performs a query against the database and returns a string stating either ‘Email address exists’ or ‘Email address available’ – I realise that this might allow bots to harvest email addresses, but this is just sample code used for my own learning. – It isn’t going to be production code.
Your
checkEmail()function returnsundefinedimmediately, which does not prevent the form from submitting. Your page gets reloaded before the AJAX request has the chance to even start. AJAX requests are asynchronous — they run in the background, and their callbacks are executed outside of the control flow surrounding the actual call to$.ajax(), and the callbacks’ return values are discarded.One way to accomplish what you’re trying to do, is to have the
donecallback set a flag if the check is successful and submit the form again, and have thecheckEmail()function returnfalseif the flag is not set: