Jump to content

Form submission with AJAX


aloha

Recommended Posts

I inserted the following javascript to verify my form inputs with <form method onsubmit="return(chkForm())" ......>. THe AJAX script works properly and returns an alert message when the data submitted are the same as that saved in the database. The AJAX will reset the form and return false to the form. But the form continues to submit data to the CGI script. How do we stop the script from submitting in the above scenario?

function chkForm() {	var album = document.swapForm.album;	var title = document.swapForm.title;	var artist = document.swapForm.artist;	var input = document.swapForm.file;	if (input.value == "" || album.value == "" || title.value == "" || artist.value == "") {		if (album.value == "") { alert("Please enter the album title!"); album.focus(); return(false); }		if (title.value == "") { alert("Please enter the music or song title!"); title.focus(); return(false); }		if (artist.value == "") { alert("Please enter the artist's name!"); artist.focus(); return(false); }		if (input.value == "") { alert("Please submit an MP3 file for swapping!"); input.focus();  return(false); }		else { 			var str = input.value;			if (str.indexOf(".mp3") == -1) { alert("Invalid file format!"+"\n"+"We accept only MP3 music file!");  input.focus();  return(false); } 		}	}	else {		xmlHttp = GetXmlHttpObject();		if (xmlHttp == null) { alert("Browser does not support HTTP request!"); return; }		var url = "chkdata";		url = url+"?album="+album.value+"&title="+title.value+"&artist="+artist.value;		xmlHttp.onreadystatechange = stateChanged;		xmlHttp.open("GET", url, true);		xmlHttp.send(null);	}}function stateChanged() {	if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") {		var note = xmlHttp.responseText;		if (note == "") { return(true); }		else { document.getElementById("swapForm").reset(); alert(note); return(false); }	}}function GetXmlHttpObject(handler) {	var objXMLHttp = null;	if (window.XMLHttpRequest) { objXMLHttp = new XMLHttpRequest(); }	else if (window.ActiveXObject) { objXMLHttp = new ActiveXObject("Microsoft.XMLHTTP"); }	return objXMLHttp;}

Link to comment
Share on other sites

... xmlHttp.open("GET", url, true); ...
It looks like you are making the AJAX call asyncronously. This means that the script sends off the request through the XMLHTTP object and then continues on its merry way (i.e. submitting the form).Try this instead:
	...	xmlHttp.open("GET", url, false);	...

This should make your script wait for the AJAX request to return before continuing on.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...