表单提交后如何防止页面重新加载 - JQuery [英] How to prevent page from reloading after form submit - JQuery

查看:145
本文介绍了表单提交后如何防止页面重新加载 - JQuery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的应用开发课程开发一个网站,我有最奇怪的问题。

我使用了一些JQuery将表单数据发送到名为'process.php'的php页面,然后将其上传到我的数据库。奇怪的错误是,页面在提交表单时会重新加载,而我不能或者我的生活不知道如何让JQuery在后台进行。这就是使用JQuery的第一步哈哈。无论如何,我会提交所有相关的代码,让我知道如果你需要别的东西。

 < script type =text / JavaScript> 
$ b $(document).ready(function(){
$('#button')。click(function(){

var name = $( #name)。val();
var email = $(#email)。val();

$ .post(process.php,{
$ name:name,
email:email
})。complete(function(){
console.log(Success);
});
});
});
< / script>
< div class =main col-xs-9 well>
< h2 style =color:blackclass =featurette-heading>加入我们的邮件列表!< / h2>
< form id =mainmethod =postclass =form-inline>
< label for =inlineFormInput>名称< / label>
< input type =textid =nameclass =form-control mb-2 mr-sm-2 mb-sm-0id =inlineFormInputplaceholder =Jane Doe>
< label for =inlineFormInputGroup>电子邮件< / label>
< div class =input-group mb-2 mr-sm-2 mb-sm-0>
< input type =textid =emailclass =form-controlid =inlineFormInputGroupplaceholder =janedoe@email.com>
< / div>
<! - 计划在此写入成功消息 - >
< label id =success_messagestyle =color:darkred>< / label>
< button id =buttontype =submitvalue =sendclass =btn btn-primary>提交< / button>
< / form>

这是我的php,如果相关的话:

 <?php 
include'connection.php';

$名称= $ _POST ['name'];
$电子邮件= $ _POST ['email'];
$ b $ //将玩家1的分数发送给数据库
$ save1 =插入'contact_list`(`name`,`email`)VALUES('$ Name','$ Email' );

$ success = $ mysqli-> query($ save1);

if(!$ success){
die(无法输入数据:。$ mysqli->错误);

回声失败;
}

回显成功;
?>

这是日志的截图:



解决方案

< button> 元素放置在表单中时,将自动提交表单,除非另有说明。您可以使用以下两种策略:


  1. 使用< button type =button> 来覆盖默认的提交行为

  2. 在onSubmit事件中使用 event.preventDefault()来阻止表单提交
  3. >



解决方案1:


  • 优点:标记

  • 缺点:颠覆了默认的表单行为,特别是当JS被禁用时。如果用户想要点击输入提交,该怎么办?



插入额外的类型属性到您的按钮标记:

 < button id =buttontype =buttonvalue =send class =btn btn-primary>提交< / button> 



解决方案2:




  • 优点:即使禁用了JS,表单也可以工作,并且尊重标准表单UI / UX,使得至少有一个按钮用于提交



防止单击按钮时的默认表单提交。请注意,这不是理想的解决方案,因为您实际上应该在听提交事件,而不是按钮点击事件:

  $(document).ready(function(){
//听取提交按钮上的点击事件
$('#button')。click(function(e) {

e.preventDefault();

var name = $(#name)。val();
var email = $(#email ).val();

$ .post(process.php,{
name:name,
email:email
})。complete function(){
console.log(Success);
});
});
});



更好的变体:



,我们听取从< form> 元素发出的提交事件:

 <$ c $($#$> $('#main')。submit(function(e)$($) {

e.preventDefault();

var name = $(#name)。val();
var email = $(#email ).val();

$ .post(process.php,{
name:name,
email:email
})。complete function(){
console.log(Success);
});
});
});



更好的变体:使用 .serialize() 来序列化表单,但请记住添加 name 属性到你的输入:



name 属性是 .serialize )按照 jQuery的文档工作:


对于要包含在序列化字符串中的表单元素的值,元素必须具有name属性。




 < input type =textid =namename =nameclass =form-control mb-2 mr-sm- 2 mb-sm-0id =inlineFormInputplaceholder =Jane Doe> 
< input type =textid =emailname =emailclass =form-controlid =inlineFormInputGroupplaceholder =janedoe@email.com>

然后在您的JS中:



<$ p $ b $ $(document).ready(function(){
//收听< form>本身的提交事件
$('#main')。提交(函数(e){

//防止刷新页面的表单提交
e.preventDefault();

//序列化数据
var formData = $(this).serialize();

//创建AJAX请求
$ .post(process.php,formData).complete(function(){
console.log(Success);
});
});
});


I am working on a website for my app development class and I have the weirdest issue.

I am using a bit of JQuery to send form data to a php page called 'process.php, and then upload it to my DB. The weird bug is that the page reloads upon submitting the form, and I cannot or the life of me figure out how to make the JQuery go on in just the background. That is sorta of the point of using JQuery in the first place haha. Anyways, I will submit all relevant code, let me know if you need anything else.

<script type="text/JavaScript">

$(document).ready(function () {
  $('#button').click(function () {

    var name = $("#name").val();
    var email = $("#email").val();

    $.post("process.php", {
      name: name,
      email: email
    }).complete(function() {
        console.log("Success");
      });
  });
});
</script>
<div class= "main col-xs-9 well">
  <h2 style="color: black" class="featurette-heading">Join our mailing list!</h2>
  <form id="main" method = "post" class="form-inline">
    <label for="inlineFormInput">Name</label>
    <input type="text" id="name" class="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput" placeholder="Jane Doe">
    <label for="inlineFormInputGroup">Email</label>
    <div class="input-group mb-2 mr-sm-2 mb-sm-0">
      <input type="text" id="email" class="form-control" id="inlineFormInputGroup" placeholder="janedoe@email.com">
    </div>
    <!--Plan to write success message here -->
    <label id="success_message"style="color: darkred"></label>
    <button id ="button" type="submit" value="send" class="btn btn-primary">Submit</button>
  </form>

This is my php if its relevant:

<?php
  include 'connection.php';

  $Name = $_POST['name'];
  $Email = $_POST['email'];

  //Send Scores from Player 1 to Database 
  $save1   = "INSERT INTO `contact_list` (`name`, `email`) VALUES ('$Name', '$Email')";

  $success = $mysqli->query($save1);

  if (!$success) {
    die("Couldn't enter data: ".$mysqli->error);

    echo "unsuccessfully";
  }

  echo "successfully";
?>

This is a screenshot of the log:

解决方案

The <button> element, when placed in a form, will submit the form automatically unless otherwise specified. You can use the following 2 strategies:

  1. Use <button type="button"> to override default submission behavior
  2. Use event.preventDefault() in the onSubmit event to prevent form submission

Solution 1:

  • Advantage: simple change to markup
  • Disadvantage: subverts default form behavior, especially when JS is disabled. What if the user wants to hit "enter" to submit?

Insert extra type attribute to your button markup:

<button id="button" type="button" value="send" class="btn btn-primary">Submit</button>

Solution 2:

  • Advantage: form will work even when JS is disabled, and respects standard form UI/UX such that at least one button is used for submission

Prevent default form submission when button is clicked. Note that this is not the ideal solution because you should be in fact listening to the submit event, not the button click event:

$(document).ready(function () {
  // Listen to click event on the submit button
  $('#button').click(function (e) {

    e.preventDefault();

    var name = $("#name").val();
    var email = $("#email").val();

    $.post("process.php", {
      name: name,
      email: email
    }).complete(function() {
        console.log("Success");
      });
  });
});

Better variant:

In this improvement, we listen to the submit event emitted from the <form> element:

$(document).ready(function () {
  // Listen to submit event on the <form> itself!
  $('#main').submit(function (e) {

    e.preventDefault();

    var name = $("#name").val();
    var email = $("#email").val();

    $.post("process.php", {
      name: name,
      email: email
    }).complete(function() {
        console.log("Success");
      });
  });
});

Even better variant: use .serialize() to serialize your form, but remember to add name attributes to your input:

The name attribute is required for .serialize() to work, as per jQuery's documentation:

For a form element's value to be included in the serialized string, the element must have a name attribute.

<input type="text" id="name" name="name" class="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput" placeholder="Jane Doe">
<input type="text" id="email" name="email" class="form-control" id="inlineFormInputGroup" placeholder="janedoe@email.com">

And then in your JS:

$(document).ready(function () {
  // Listen to submit event on the <form> itself!
  $('#main').submit(function (e) {

    // Prevent form submission which refreshes page
    e.preventDefault();

    // Serialize data
    var formData = $(this).serialize();

    // Make AJAX request
    $.post("process.php", formData).complete(function() {
      console.log("Success");
    });
  });
});

这篇关于表单提交后如何防止页面重新加载 - JQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆