Ajax for newbies: verify if record exists in database table using prototype and PHP.
Create a new page (index.php). Add this line of code in the tag of index.php to include prototype framework:
<script type="text/javascript" src="prototype.js"> </script>
<input type="text" name="name" id="name" /> <input type="submit" value="Verify" onclick="javascript:verifyName()"/> <span id="result" style="color:#009900"> </span>
Create a new page (verify.php). This page contains a simple query to verify if record exists in database table (Users):
<?php
if(isset($_GET['name']))
{
/* Connection to Database */
include('config.php');
/* Remove HTML tag to prevent query injection */
$name = strip_tags($_GET['name']);
$sql = 'SELECT *
FROM Users
WHERE user_name="'.$name.'"';
$result=mysql_query($sql);
if(mysql_num_rows($result)&gt;0)
echo $name.'the username already exists!';
else
echo $name.'the username does not exist!';
}
else
{
echo '0';
}
?>
This code enable ajax request with prototype. Add this lines of code in the index.php file:
<script type="text/javascript">
function verifyName()
{
var name = $F('name');
var url = 'verify.php?';
var pars = 'name=' + name;
new Ajax.Request(url, {method: 'get',parameters: pars,onComplete: showResponse});
}
function showResponse(originalRequest)
{
$('result').innerHTML = originalRequest.responseText;
}
</script>
We pass the value we want to search for to index.php using this simple code:
method: 'get',parameters: pars
onComplete we show in the tag the response text, returned by the Ajax Request method:
if(mysql_num_rows($result)&amp;gt;0) echo $name.'the username already exists!'; else echo $name.'the username does not exist!';
The echo function returns the response text which is displayed in the “result” container in index.php, without ever leaving the page.
RSS feed for comments on this post · TrackBack URI
Leave a reply