22

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:

screenshot of log

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Casey.PhillipsTMC
  • 293
  • 1
  • 3
  • 10

2 Answers2

80

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");
    });
  });
});
Terry
  • 63,248
  • 15
  • 96
  • 118
  • 1
    Use #2 if want form to submit using keyboard – charlietfl Aug 11 '17 at 11:32
  • @charlietfl You are correct: in terms of user accessibility, solution #2 is the way to go ;) also updated answer for a better solution, i.e. listening to submit event instead of button click. – Terry Aug 11 '17 at 11:33
  • 4
    @Terry by far one of the most helpful answers I have ever gotten on here. I am teaching the class to myself as a Directed Study so this is more than helpful, to be honest! I have seen a lot of this stuff out there in my google searches but never explained this well! Thank you! – Casey.PhillipsTMC Aug 11 '17 at 17:36
  • @Terry seriously man...you're a life saver!!! I spent literally 6hrs trying so many different things (including other stackoverflow suggestions). I was almost about to give up and cry (metaphorically). I am sooooo glad you're solution worked. I will buy you a few drinks if we ever bump into each other. – theQuestionMan Sep 11 '20 at 01:04
  • @Terry I really wanted the form and submit type button because a submit type button prompts for required fields. So while solution 1 didn't work, solution 2 worked like a charm. Again, drinks and lunch on me!!! – theQuestionMan Sep 11 '20 at 01:09
0

clear the previous state when loading the page.... add this to document.ready function.

if ( window.history.replaceState ) {
    window.history.replaceState( null, null, window.location.href );
}
Gayan Chinthaka
  • 521
  • 6
  • 5