问题
I have the following code on my homepage for people to sign up for a newsletter - the email address is entered into a newsletter_emails table and on clicking GO button a thank you popup appears.
Email: <input type="text" name="email" value="" id="email" />
<input type="button" name="submit" onclick="submit_me()" value="GO" />
<script type="text/javascript" charset="utf-8">
function submit_me() {
var email_value = $('#email').val();
$.post("ajax_subscribe.php", { email: email_value }, function(response) {
if (response!='') {alert(response)};
alert('Thank You !');
});
}
The page where the email is inserted into the database (ajax_subcribe.php) is as follows:
<?php
$host = "xxxx";
$user = "xxxx";
$password = "xxxx";
$database = "xxxx";
$server = mysql_connect($host, $user, $password);
$connection = mysql_select_db($database, $server);
function sql_quote($value) {
$value = str_replace('<?','',$value);
$value = str_replace('script','',$value);
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
if (!is_numeric($value)) {
$value = "'" . mysql_real_escape_string($value) . "'";
} else {
if ((string)$value[0] == '0') {
$value = "'" . mysql_real_escape_string($value) . "'";
}}
return $value;
}
$q = "INSERT INTO newsletter_emails (email,category) VALUES (".sql_quote($_POST['email']).",'1')";
mysql_query($q);
?>
While this all works well, there is no validation on the ajax_subscribe page - I have the following javascript on another part of my site.
<script type="text/javascript">
function validate(form_id,email) {
var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var address = document.forms[form_id].elements[email].value;
if(reg.test(address) == false) {
alert('Invalid Email Address');
return false;
}
}
</script>
I would like to incorporate such validation into this newsletter form so that on clicking the Go button, either the "thank you" popup or the "invalid email" popup appears. For some reason I cant get it working even if I enter form id="form_id", etc etc. I have basically been able to get on side or the other working but not both together!
Any advice much appreciated thanks JD
回答1:
use something like this in your form to call your JS validation code
<form method="GET" action="javascript:Validate(id)">
For this to work your JS should always return false. Use JS location to redirect on success.
来源:https://stackoverflow.com/questions/6551242/form-validation-for-newsletter-signup-with-javascript-popup