View Full Version : Call AJAX function when submit form

01-29-2009, 04:57 PM

I am having problems with a form I want to call an Ajax function when the submit button is selected. I want to validate the form using javascript and then to call a PHP file to process the form data and then reurn a message to the page when successful.

It works to a point where it validates the form but then instead of doign the AJAX, it tries to do the form action and refreshes the page with the #. I am alerting the message 'No errors' and it works until the ajax response part.

Anyoen any ideas what Im doing wrong? Do I need to disable the "action='#'" onthe form somehow?

the code is below:

<form name="register" method="POST" action="#" style="margin:5px 0 " onsubmit="return registerEmail(this);">
input type="text" name="email" value="Email Address" class="newsletter"/>
<input type="image" name="register" src="images/register.jpg" alt="Register" class="submit" style="margin-right:15px"/>

function registerEmail(form) {

var error = false;

var strURL="register.php?email="+form.email.value;

var req = getXMLHTTP();

if ((form.email.value == "")||(form.email.value == "Email Address")) {
alert("Please enter your email address.");
form.email.focus( );
error = true
return false;

if (validate_email(form.email.value)==false){
alert("Not a valid e-mail address!");
error = true
return false;

if (!error){
if (req) {

if (req.readyState == 4) {
alert('no errors');
if (req.status == 200) {

document.getElementById('confirmOK').innerHTML = 'Thank you, you have now been registered for our newsletter.';
req.open("GET", strURL+'&bustcache='+new Date().getTime(), true);

01-29-2009, 05:37 PM
If you do not want the form to submit, you need to return false at the end of your script.


01-30-2009, 09:23 AM
Thank you that works. Although the code after

if (req.readyState == 4) {
if (req.status == 200) {

isnt being executed for some reason.

01-30-2009, 05:57 PM
Well you haven't shown an onreadystatechange handler anywhere - you'll want to place that if block inside that.

01-31-2009, 05:17 PM
I'm running into the same thing. Initially ajax fires the form. The result could be the same form (eg: pwd is invalid). If the result is the same form THEN submitting form is NOT handled via ajax but acts like a typical form submit targeting the page (page reloads). I'm an ajax / mootools noob. Simplified code looks like this...

$('form_changepwd').addEvent('submit', function(e) {
this.set('send', { onComplete: function(response) {
$('container_div').set('html', response);

My form has a submit btn (<input type="submit".... />)