Submitting a form with ajax

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Carsten
Forum Newbie
Posts: 5
Joined: Wed Nov 09, 2005 6:46 am

Submitting a form with ajax

Post by Carsten »

Hello!

I need a little help with designing a form with ajax.

What I want: this form should be used to save user-data by an administrator. For every user a certain id must be given by the administrator, it's not possible to use an auto_increment from mysql or something like that. Basic javascript validation is not the problem. But I want to use ajax to check in the background if the id is already used or not by using a simple COUNT()-query in the database. If it's used, send an errormessage.

It's no problem to access the check-script with ajax but I don't get it how to stop the form submitting.

Here are the basic scripts:

The HTML-Form:

Code: Select all

<div id="errorMsg">
</div>
<form action="index.php" method="post" id="partnerform" onsubmit="request();">
...
</form>
The check.php:

Code: Select all

<?php
//... some work before
$xml = '<?xml version="1.0" encoding="iso-8859-1"?>';

$pIDCnt = $db->CountRows('pID', 'partnerprog_partner', 'pID = '.$_POST['pID']); // Counts ids
if ( $pIDCnt > 0 )	# id already used?
	$errMsg[] = '<error>User-ID is already in use!</error>';

if ( count($errMsg) > 0 )
{
	$xml .= "<suggest xmlns='http://www.w3.org/1999/xhtml'>\n";
	$xml .= implode("\n", $errMsg)."\n</suggest>";
}
else
	$xml .= "<suggest xmlns='http://www.w3.org/1999/xhtml'></suggest>\n";

header("Content-type: text/xml");
echo $xml;
?>
And here are the important javascript functions:

Code: Select all

function request()
{
	document.getElementById('submit').disabled = true;
	var contentType = "application/x-www-form-urlencoded; charset=UTF-8";
	var elements = document.getElementById('partnerform').elements;
	var pairs = new Array();
	var params;
	
	for (var i = 0; i < elements.length; i++)
	{
		if ((name = elements[i].name) && (value = elements[i].value))
			pairs.push(name + "=" + encodeURIComponent(value));
	}
	
	params = pairs.join("&");

	http.onreadystatechange = handleResponse;
	http.open('POST', 'check.php', true);
	http.setRequestHeader("Content-Type", contentType);
	http.send(params);
}

function handleResponse()
{
    if ( http.readyState == 4 )
	{
		if (http.status == 200)
		{
			list = http.responseXML.getElementsByTagName("suggest")
			var l = list[0].getElementsByTagName("error").length;

			if ( l > 0 )
			{
				var os = '';
				for ( i = 0; i < l; i++ )
					os = os + list[0].getElementsByTagName("error")[i].firstChild.nodeValue + '<br />';

				document.getElementById('errorMsg').innerHTML = os;
				document.getElementById('errorMsg').style.display = "block";
				window.scrollTo(0,0);
				document.getElementById('submit').disabled = false;
				return false; /* Do not send the form */
			}
			else
				return true; /* Everything okay, submit the form */
		}
    }
}
So, the form should be send when the id is not used, but not when it's in use. How do I get it?
Grim...
DevNet Resident
Posts: 1445
Joined: Tue May 18, 2004 5:32 am
Location: London, UK

Post by Grim... »

Three suggestions:
1) Why not use onblur () to check as soon as the id box is filled, and only display the submit button if the ID is cool
2) Scrap ajax, and just check on the next page, returning all the variables back into the form if there is a problem
3) Don't have a submit button, use a normal button to run your javascript.
Carsten
Forum Newbie
Posts: 5
Joined: Wed Nov 09, 2005 6:46 am

Post by Carsten »

Thanks for your answer.
Grim... wrote:1) Why not use onblur () to check as soon as the id box is filled, and only display the submit button if the ID is cool
The check for a used id is just an example. There are far more checks to do and I personally think that checking all at once is better.
Grim... wrote:2) Scrap ajax, and just check on the next page, returning all the variables back into the form if there is a problem
It's the way the form is handled when javascript is off. But the main reason for ajax: I want to train ajax on this example. :) And I didn't found any example or tutorial with this specific problem.
Grim... wrote:3) Don't have a submit button, use a normal button to run your javascript.
Hm... Doesn't seem to make any difference. Or do I have to used the button in any other way than "onclick=()"?
Carsten
Forum Newbie
Posts: 5
Joined: Wed Nov 09, 2005 6:46 am

Post by Carsten »

Well, I got it now. But in another way I originally thought. Perhaps there seems to be a misunderstanding by myself what ajax is capable to do and what not.

I looked into several tutorials and all they were doing is replacing the form with other html elements. I thought it would be possible to decide - depending if my check-script returns errorcodes or not - to submit the form to a following script and there save all data OR to prevent the form from submitting. All my trials could give me one of the two possibilities but not both.

I modified my scripts now. The "check.php" does his work and when there are no errors, all data is saved in the database and tags named "<success>" (instead of "<error>") are returned as xml. The form is than replaced by the contents of the "<success>" tags, like all the tutorials are doing.

So, I get it right that to send a TRUE or FALSE back to the form is not possible to control submitting the form?
Post Reply