Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent page from reloading after form submit - JQuery

Tags:

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

like image 559
Casey.PhillipsTMC Avatar asked Aug 11 '17 11:08

Casey.PhillipsTMC


People also ask

How do I stop reloading form?

What preventDefault() does is that it tells the browser to prevent its default behaviour and let us handle the form submitting event on the client side itself.

How do you stay on the same page after submit in HTML?

You could include a hidden iframe on your page and set the target attribute of your form to point to that iframe. There are very few scenarios where I would choose this route. Generally handling it with javascript is better because, with javascript you can...


1 Answers

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");     });   }); }); 
like image 60
Terry Avatar answered Sep 27 '22 22:09

Terry