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>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;
?>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 */
}
}
}