How to prevent page from reloading after form submit - JQuery

Casey.PhillipsTMC

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="[email protected]">
    </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:

screenshot of log

Terry

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="[email protected]">

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");
    });
  });
});

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Prevent page form reloading after reroute Laravel

Prevent modal from reloading after form submission

Submit form without reloading page

Submit form without page reloading

How to submit form data in the same page in WordPress without reloading the page?

How can I keep the page from reloading on form submit, and also show a small text saying "successfully registered"

jquery prevent box to close after submit a form

How to prevent jQuery .submit from firing when form errors

How to prevent jquery submit button from refreshing the HTML page?

Ajax - page reloading on submit with jquery

How to add a AJAX submit form inside a notification without reloading the page?

How to submit form without reloading the page using Spring Boot Async?

Allow form to send POST request but prevent page from reloading - Javascript

How to stop redirect from partial page after form submit

Prevent page from reloading after onchange a select menu

Django: How to prevent a page from reloading when I click button with Ajax/Javascript? (not jQuery)

jquery - how to prevent submit form continuously

How can I stop my form from reloading on submit?

Submit form without page reloading, and link to javascript

Submit Form Data without Reloading page

Complete form submit action without reloading the page

Get page content from separate page into div on form submit without reloading current page

Prevent page reload and redirect on form submit ajax/jquery

How to stay in same page after submit form

How can i display alert after sending form and reloading page?

How to prevent html from clearing after submit

how to submit form how to get session count without reloading page on form submission

How to prevent form submit?

Populate a form after submit with jQuery and ajax from