通讯:
<form id="form-search" method="post" action="<?php echo $_SERVER['PHP_SELF'];?>"> <span><span class="style2">Enter you email here</span>:</span> <input name="email" type="email" id="email" required/> <input type="submit" value="subscribe" class="submit" onclick="return fun()" /> </form> <?php mysql_connect("localhost","",""); mysql_select_db(""); error_reporting(E_ALL && ~E_NOTICE); $email=$_POST['email']; $sql="INSERT INTO newsletter_email(email) VALUES ('$email')"; $result=mysql_query($sql); if($result){ echo "You have been successfully subscribed."; } if(!$sql) die(mysql_error()); mysql_close(); ?>
但是我想通过Ajax将我的电子邮件插入数据库。我不希望页面被重定向,因为每次刷新页面时,都会将空值插入数据库。
我只希望我的电子邮件通过Ajax插入数据库,然后再发送电子邮件,即
<input name="email" type="email" id="email" required/> <input type="submit" value="subscribe" class="submit" onclick="return fun()" />
应该消失,并且应该有“您已成功订阅”行。
任何简短的代码将非常有用..预先感谢您:)
尝试这个:
$(document).on('click','#save',function(e) { var data = $("#form-search").serialize(); $.ajax({ data: data, type: "post", url: "insertmail.php", success: function(data){ alert("Data Save: " + data); } }); });
和在 insertmail.php:
insertmail.php:
<?php if(isset($_REQUEST)) { mysql_connect("localhost","root",""); mysql_select_db("eciticket_db"); error_reporting(E_ALL && ~E_NOTICE); $email=$_POST['email']; $sql="INSERT INTO newsletter_email(email) VALUES ('$email')"; $result=mysql_query($sql); if($result){ echo "You have been successfully subscribed."; } } ?>
不要使用mysql_已弃用的。
mysql_
another method:
实际上,如果您的问题是将空值插入数据库,则尝试此操作,这里不需要ajax。
<?php if($_POST['email']!="") { mysql_connect("localhost","root",""); mysql_select_db("eciticket_db"); error_reporting(E_ALL && ~E_NOTICE); $email=$_POST['email']; $sql="INSERT INTO newsletter_email(email) VALUES ('$email')"; $result=mysql_query($sql); if($result){ //echo "You have been successfully subscribed."; setcookie("msg","You have been successfully subscribed.",time()+5,"/"); header("location:yourphppage.php"); } if(!$sql) die(mysql_error()); mysql_close(); } ?> <?php if(isset($_COOKIE['msg'])){?> <span><?php echo $_COOKIE['msg'];setcookie("msg","",time()-5,"/");?></span> <?php }?> <form id="form-search" method="post" action="<?php echo $_SERVER['PHP_SELF'];?>"> <span><span class="style2">Enter you email here</span>:</span> <input name="email" type="email" id="email" required/> <input type="submit" value="subscribe" class="submit"/> </form>