Preventing Duplicate Entries - Ajax Not returning error. PHP MySQL jQuery
I'm trying to prevent duplicate entires in my DB for a newsletter submissions form. I'm successfully preventing the duplicate entries, but I haven't been able to revise my the jQuery to print the error. I've included the PHP just incase I'm missing something there... Any help would be appreciated!
jQuery:
submitHandler: function(form) {
jQuery(form).ajaxSubmit({
开发者_开发知识库 success: function() {
$('#newsletterForm').html("<div id='success-message'></div>");
$('#success-message').html("<p><strong>Thank you.</strong> <br/>You've been added to our list and will hear from us soon!</p>");
},
error: function() {
$('#newsletterForm').html("<div id='success-message'></div>");
$('#success-message').html("<p><strong>That email already exists.</strong> <br/>Please enter another email address.</p>");
}
});
}
PHP:
if(isset($_POST['submit'])) {
if(trim($_POST['email']) == '') {
$hasError = true;
} else if (!eregi("^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
$hasError = true;
} else {
$email = trim($_POST['email']);
}
if(!isset($hasError)) {
$con = mysql_connect("xxx.xxx.xxx.xxx","user","pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("myDB", $con);
$query = "SELECT COUNT(id) AS mycount FROM newsletter WHERE email = '$email'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
if($row['mycount'] == 0) {
$query = "INSERT INTO newsletter (email,dt) VALUES ('$email',NOW())";
mysql_query($query) or die ("Error writing to database");
} else {
echo "I'm sorry our database already contains that email address. Please use a new email address to continue.";
}
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
mysql_close($con);
}
}
The error only gets called if your AJAX request fails (such as a 404).
Inside your success: function() { }
you'll need to determine if what your PHP script returned was a success message, or error message. The easiest way to do this is with JSON instead of plain text.
To do this, in your PHP instead of echoing a string, do..
echo json_encode(array('result'=>'success','response'=>'Everything worked');
or..
echo json_encode(array('result'=>'error','response'=>'Already exists');
Then in your ajax, set the dataType to 'json' and in your success function, you can then access the JSON as an object.
Instead of echoing out the messages, why can't you just print out a JSON representation of what happened? This will allow you to directly manipulate the object in JavaScript.
Remember: jQuery is not a language.
精彩评论