Ajax Form Validation - Reload Problem

Hi all

I’ve been working on two separate ways to validate my comments form:

  1. The jQuery validation plugin
  2. Ajax and PHP

If anybody knows how to submit the form without reloading the page using jQuery validation plugin, please let us know… pulling my hair out for 2 days.

I’m currently working on - Ajax PHP method

club.php

ajax.js

add_review.js

<form name=“form” method=“post” id=“commentForm” action=“add_review.php”>

The form works when I submit it and returns the XML data with a error or success message, but on a new page(add_review.php), it’s supposed to display in:

[INDENT]<div id=“results”></div>[/INDENT] on club.php

Why is it showing the form messages on add_review.php instead of loading the messages/dom in the <div> on club.php

Any suggestions? :cool:

Most validators prevent the form from submitting by returning false when validation fails. If you want to prevent it from submitting regardless of whether validation passes or fails, you could set a flag indicating success or failure and then unconditionally return false.

Thanks WWW not sure which one to post now, jQuery seems to do all the work for you, but this also has the page reload problem. I’m not really a JS expert so any help would be great.

I’ll concentrate on the Ajax as above for now.

ajax.js - this just checks if the dom is supported
add_review.js - this holds my 2 functions used on the form, can you see anything out of place?

// JavaScript Document
window.onload = init;
function init() {
	var ajax = getXMLHttpRequestObject();
	if (ajax) {
		if (document.getElementById('results')) {
			document.getElementById('commentForm').onsubmit = function() {
				
			ajax.open('post', 'add_review.php');
			ajax.onreadystatchange = function() {
				handleResponse(ajax);
			}
			var fields = ['venue_id', 'publisher', 'comments'];
			for (var i = 0; i < fields.length; i++) {
				fields[i] = fields[i] + '=' + 
				encodeURIComponent(document.getElementById(fields[i]).value);
			}
			var values = fields.join('&');
			ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			
			ajax.send(values);
			return false;
			
			} 
		} // End of DOM check

	} // End of ajax IF.

function handleResponse(ajax) {
		if (ajax.readyState == 4) {
			if ((ajax.status == 200) || (ajax.status == 304) ) {
		var results = document.getElementById('results');
		document.getElementById('publisher_label').className = 'title';
		document.getElementById('comments_label').className = 'title';
		
		var data = ajax.responseXML;
		var message = data.getElementsByTagName('result');
		var errors = data.getElementsByTagName('error');
		var temp = false;
		
		for (var i = 0; i < errors.length; i++) {
			temp = errors[i].firstChild.nodeValue;
			document.getElementById(temp + '_label').className = 'error';
		}
		results.innerHTML = message[0].firstChild.nodeValue;
		results.style.display = 'block';
			} else {
				document.getElementById('commentForm').submit();
			}
		} // End of readyState IF.
} // End of handleResponse() function
		
} // End of init() function.

add_review.php code below and my INSERT commands for DB

<?php # add_review.php
header("Content-Type: text/xml");
echo '<?xml version="1.0" encoding="utf-8"
standalone="yes" ?>
<response>
';
require_once('includes/mysql_connect.inc.php');
$error = false;
if (!empty($_POST['publisher'])) {
..etc 

What do you think? :cool:

Do some debugging. Test your conditional statements to make sure they’re doing what you expect them to do. Test your variables too, to make sure they contain the values you expect them to.

For example, to test an if statement, put an alert(‘hi!’) inside the if statement. Now run the code. Now you know if that if statement was true. Do this strategically for all your code.

A debugger like firebug can help make doing this much faster if your familiar with it(set breakpoints). If not, you can do it by hand with little effort.

The goal is to figure out what your code is doing. Only then, can you compare to what you wanted it to do. Then you can fix it.

Make sure you’re paying attention to error messages in the browsers error console too.

Thank crmalibu

I’ve tried everything. Just can’t figure this out… cracking me up.

I also have the validation plugin running as mentioned above, this is my second choice but if anybody knows how to display a success message without reloading the page :slight_smile:

$(document).ready(function() { 
	  $("#commentForm").validate({ 
	    rules: { 
	      publisher: { 
	      required: true
	      }, 
	      comments: { 
	      required: true 
	      } 
	    }, 
	    messages: { 
		  publisher: "please enter your name.",
		  comments: "please enter your review"
	    } 
	  }); 
	});

Thanks guys :cool:

Have you debugged your handleResponse() function?

Which if statements are true, and which are false?
What is the value of ajax.status?

No. :slight_smile: I don’t know what or where to type the code, bit of a JS novice, I’ve been working through a book a have, could you show me what to add in a example so I can test it?


function handleResponse(ajax) {
    if (ajax.readyState == 4) {
        alert("my ajax.readyState == 4 was true");
        if ((ajax.status == 200) || (ajax.status == 304) ) {
            alert("my (ajax.status == 200) || (ajax.status == 304) was true");
        } else {
            alert("my (ajax.status == 200) || (ajax.status == 304) was false");
            alert("Since i assumed the value was something, and the assumption was wrong, it might be useful to see what the value is");
            alert(ajax.status);
        }
    }
} // End of handleResponse() function

Do a search on the topic of debugging. It will save you countless hours of scratching your head. Try to find some tutorials or basics. Maybe your book covers it.