表单提交与AJAX传递表单数据到PHP没有页面刷新
任何人都可以告诉我为什么这个代码不工作?
<html> <head> <script src="jquery-1.9.1.js"></script> <script> $(function () { $('form').bind('submit', function () { $.ajax({ type: 'post', url: 'post.php', data: $('form').serialize(), success: function () { alert('form was submitted'); } }); return false; }); }); </script> </head> <body> <form> <input name="time" value="00:00:00.00"><br> <input name="date" value="0000-00-00"><br> <input name="submit" type="button" value="Submit"> </form> </body> </html>
当我推送提交没有任何反应。 在接收的php文件中,我使用$ _POST ['time']和$ _POST ['date']将数据放在mysql查询中,但是只是没有获取数据。 有什么build议么? 我假设这是提交button,但我无法弄清楚
表单正在提交ajax请求之后。
<html> <head> <script src="jquery-1.9.1.js"></script> <script> $(function () { $('form').on('submit', function (e) { e.preventDefault(); $.ajax({ type: 'post', url: 'post.php', data: $('form').serialize(), success: function () { alert('form was submitted'); } }); }); }); </script> </head> <body> <form> <input name="time" value="00:00:00.00"><br> <input name="date" value="0000-00-00"><br> <input name="submit" type="submit" value="Submit"> </form> </body> </html>
<html> <head> <script src="jquery-1.9.1.js"></script> <script> $(function () { $('form').bind('click', function (event) { event.preventDefault();// using this page stop being refreshing $.ajax({ type: 'POST', url: 'post.php', data: $('form').serialize(), success: function () { alert('form was submitted'); } }); }); }); </script> </head> <body> <form> <input name="time" value="00:00:00.00"><br> <input name="date" value="0000-00-00"><br> <input name="submit" type="submit" value="Submit"> </form> </body> </html>
PHP
<?php $time=""; $date=""; if(isset($_POST['time'])){$time=$_POST['time']} if(isset($_POST['date'])){$time=$_POST['date']} echo $time."<br>"; echo $date; ?>
JS代码
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/ libs/jquery/1.3.0/jquery.min.js"> </script> <script type="text/javascript" > $(function() { $(".submit").click(function() { var time = $("#time").val(); var date = $("#date").val(); var dataString = 'time='+ time + '&date=' + date; if(time=='' || date=='') { $('.success').fadeOut(200).hide(); $('.error').fadeOut(200).show(); } else { $.ajax({ type: "POST", url: "post.php", data: dataString, success: function(){ $('.success').fadeIn(200).show(); $('.error').fadeOut(200).hide(); } }); } return false; }); }); </script>
HTML表单
<form> <input id="time" value="00:00:00.00"><br> <input id="date" value="0000-00-00"><br> <input name="submit" type="button" value="Submit"> </form> <span class="error" style="display:none"> Please Enter Valid Data</span> <span class="success" style="display:none"> Form Submitted Success</span> </div>
PHP代码
<?php if($_POST) { $date=$_POST['date']; $time=$_POST['time']; mysql_query("SQL insert statement......."); }else { } ?>
从这里采取
这是一个很好的jQuery插件,通过ajax提交表单:
http://malsup.com/jquery/form/
其如下简单:
<script src="http://malsup.github.com/jquery.form.js"></script> <script> $(document).ready(function() { $('#myForm').ajaxForm(function() { alert('form was submitted'); }); }); </script>
它使用表单行为作为发布位置。 不是你用自己的代码不能实现这个,但是这个插件对我来说工作得非常好!
JS代码
$("#submit").click(function() { //get input field values var name = $('#name').val(); var email = $('#email').val(); var message = $('#comment').val(); var flag = true; /********validate all our form fields***********/ /* Name field validation */ if(name==""){ $('#name').css('border-color','red'); flag = false; } /* email field validation */ if(email==""){ $('#email').css('border-color','red'); flag = false; } /* message field validation */ if(message=="") { $('#comment').css('border-color','red'); flag = false; } /********Validation end here ****/ /* If all are ok then we send ajax request to email_send.php *******/ if(flag) { $.ajax({ type: 'post', url: "email_send.php", dataType: 'json', data: 'username='+name+'&useremail='+email+'&message='+message, beforeSend: function() { $('#submit').attr('disabled', true); $('#submit').after('<span class="wait"> <img src="image/loading.gif" alt="" /></span>'); }, complete: function() { $('#submit').attr('disabled', false); $('.wait').remove(); }, success: function(data) { if(data.type == 'error') { output = '<div class="error">'+data.text+'</div>'; }else{ output = '<div class="success">'+data.text+'</div>'; $('input[type=text]').val(''); $('#contactform textarea').val(''); } $("#result").hide().html(output).slideDown(); } }); } }); //reset previously set border colors and hide all message on .keyup() $("#contactform input, #contactform textarea").keyup(function() { $("#contactform input, #contactform textarea").css('border-color',''); $("#result").slideUp(); });
HTML表单
<div class="cover"> <div id="result"></div> <div id="contactform"> <p class="contact"><label for="name">Name</label></p> <input id="name" name="name" placeholder="Yourname" type="text"> <p class="contact"><label for="email">Email</label></p> <input id="email" name="email" placeholder="admin@admin.com" type="text"> <p class="contact"><label for="comment">Your Message</label></p> <textarea name="comment" id="comment" tabindex="4"></textarea> <br> <input name="submit" id="submit" tabindex="5" value="Send Mail" type="submit" style="width:200px;"> </div>
PHP代码
if ($_SERVER['REQUEST_METHOD'] == 'POST') { //check if its an ajax request, exit if not if (!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') { //exit script outputting json data $output = json_encode( array( 'type' => 'error', 'text' => 'Request must come from Ajax' )); die($output); } //check $_POST vars are set, exit if any missing if (!isset($_POST["username"]) || !isset($_POST["useremail"]) || !isset($_POST["message"])) { $output = json_encode(array('type' => 'error', 'text' => 'Input fields are empty!')); die($output); } //Sanitize input data using PHP filter_var(). $username = filter_var(trim($_POST["username"]), FILTER_SANITIZE_STRING); $useremail = filter_var(trim($_POST["useremail"]), FILTER_SANITIZE_EMAIL); $message = filter_var(trim($_POST["message"]), FILTER_SANITIZE_STRING); //additional php validation if (strlen($username) < 4) { // If length is less than 4 it will throw an HTTP error. $output = json_encode(array('type' => 'error', 'text' => 'Name is too short!')); die($output); } if (!filter_var($useremail, FILTER_VALIDATE_EMAIL)) { //email validation $output = json_encode(array('type' => 'error', 'text' => 'Please enter a valid email!')); die($output); } if (strlen($message) < 5) { //check emtpy message $output = json_encode(array('type' => 'error', 'text' => 'Too short message!')); die($output); } $to = "info@wearecoders.net"; //Replace with recipient email address //proceed with PHP email. $headers = 'From: ' . $useremail . '' . "\r\n" . 'Reply-To: ' . $useremail . '' . "\r\n" . 'X-Mailer: PHP/' . phpversion(); $sentMail = @mail($to, $subject, $message . ' -' . $username, $headers); //$sentMail = true; if (!$sentMail) { $output = json_encode(array('type' => 'error', 'text' => 'Could not send mail! Please contact administrator.')); die($output); } else { $output = json_encode(array('type' => 'message', 'text' => 'Hi ' . $username . ' Thank you for your email')); die($output); }
这个页面有一个更简单的例子http://wearecoders.net/submit-form-without-page-refresh-with-php-and-ajax/
type="button
”
应该
type="submit"
在事件处理中,将事件的对象传递给函数,然后添加语句,即event.preventDefault();
这将传递数据到网页而不刷新它。