I've added some validation to my form to avoid any duplicate name entries in my database. I have a simple mysql
table with 35 entries. Using jquery $.post
I connect to the db, check to see if the name from an input type='text'
matches a name from the name
field in the table. It works pretty well, but if you repeatedly search for names that are in the db, the code eventually breaks and Chrome brings up this message:
Here is my html:
<table id="details_table">
<tr>
<td>Please choose a username:</td>
<td><input type="text" id="name" name="name" autocomplete="off" maxlength="10"></td>
<td id="text"></td>
</tr>
<tr>
<td>Please select your age range:</td>
<td><select id="option01" name="age">
<option value="0">Please Select</option>
<option value="0_14">0-14</option>
<option value="15_24">15-24</option>
<option value="25_54">25-54</option>
<option value="55_64">55-64</option>
<option value="65_over">65 or greater</option>
</select></td>
<td id="age"></td>
</tr>
<tr>
<td>Please select your gender:</td>
<td><select id="option02" name="gender">
<option value="0">Please Select</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select></td>
<td id="gender"></td>
</tr>
<tr>
<td>Please select your listening device:</td>
<td><select id="option03" name="device">
<option value="0">Please Select</option>
<option value="headphones">Headphones</option>
<option value="speakers">Speakers</option>
</select></td>
<td id="device"></td>
</tr>
</table>
Here is my JQuery:
$(function() {
$('#name').keyup(function (evt) {
$('#text').html("");
var name = $('#name').val();
$.post('/context_survey/includes/process_name.php', {name_check: name}, function(rows_returned) {
if (rows_returned != 0) {
$('#text').html("<b style='color:red'>Name already exists!</b>");
$('#name').val("");
}
});
});
$('#option01').change(function (evt) {
$('#age').html("");
});
$('#option02').change(function (evt) {
$('#gender').html("");
});
$('#option03').change(function (evt) {
$('#device').html("");
});
});
Here is my PHP:
require_once("connect.php");
if (!empty($_POST['name_check'])) {
$name = $_POST['name_check'];
$sql = "SELECT name FROM users WHERE name='{$name}'";
if ($result = $db -> query($sql)) {
$num_rows = $result -> num_rows;
echo $num_rows;
}
$db -> close();
}