I’m trying to update a database using html form + jquery + php
When I click on the Submit button on the form it works but it is adding two same records in the database for each click.
I can’t find out what is going wrong and therefore I’m posting the whole script I’m using here. If anyone can find the problem then please point it out.
Here are the scripts I’m using
HTML
<div id="result" class="results"></div>
<form id="person-form" class="person-form" method="post">
<fieldset>
<legend><strong>Add a new member</strong></legend>
<table>
<tr><td><label for="Name" >Name</label></td>
<td colspan="2"><input type="text" name="name" value="Enter the Name, 55 char max." /></td></tr>
<tr><td><label for="email">Email</label></td>
<td colspan="2"><input type="text" name="email" value="Enter the email" /></td></tr>
<tr><td><label for="subscribe">Subscribe</label></td>
<td><input type="checkbox" name="subscribe" value="Yes" /></td>
<td><input type="submit" value="Add member" id="add-member" class="add-member"/></td></tr>
</table>
<div style="clear:both;"></div>
</fieldset>
</form>
jQuery
$("#add-url").live("click", function() {
var name = $('input[name=name]').val();
var email = $('input[name=email]').val();
var subs = $('input[name=subscribe]:checkbox:checked').val();
var data = 'name='+name+'&email='+email+'&subs='+subs;
$.post(add_member_script.ajaxurl, data, function(data) {
$('#results').html(data);
});
return false;
});
And PHP
$connect = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$connect){
die('Could not connect: ' . mysql_error());
}
mysql_select_db(DB_NAME, $connect);
if (empty($_POST['name']) || empty($_POST['email'])){
echo 'enter some value';
} else {
if($_POST['subs']== 'yes') {
$sql="INSERT INTO $table (name, email, subs) VALUES ('$_POST[name]','$_POST[email]','$_POST[subs]')";
} else {
$sql="INSERT INTO $table (name, email) VALUES ('$_POST[name]','$_POST[email]')";
}
if (!mysql_query($sql,$con)){
mysql_error();
} else {
list_links_table ();
}
mysql_close($con);
die();
}
It looks like the form may be getting submitted both via AJAX and the “normal” way. To make sure, add
onsubmit="return false"to the form tag:Alternately, you can remove all your JS and allow the form to submit normally, and see if the duplication persists.