Home > other >  Submit form without page reload using jQuery - not working
Submit form without page reload using jQuery - not working

Time:12-29

I am submitting a form using jQuery because I don't want a page to reload. Only validation works, but the form submission doesn't. The page still reloads, there's not a success function and it adds data to the URL like it's a GET method. I just can't figure out what's wrong in the jQuery form submission code.

// Form Validation - WORKS

$(document).ready(function() {

  $("form").validate({

    errorPlacement: function(error, element) {
      $(element)
        .closest("form")
        .find("label[for='"   element.attr("id")   "'] > span")
        .append(error);
    },

    errorElement: "span",

    rules: {
      firstname: "required",
      lastname: "required",
      email: {
        required: true,
        email: true
      },
      subject: "required",
      msg: "required",
      checkbox: "required",
    },

    messages: {
      firstname: "*required",
      lastname: "*required",
      email: {
        required: "*required",
        email: "*invalid email address"
      },
      subject: "*required",
      msg: "*required",
      checkbox: "*required",
    },

    submitHandler: function(form) {
      form.submit();
    }
  });

});


// Form Submit - DOESN'T WORK

$('form').on('submit', function(e) {

  e.preventDefault();

  $.ajax({
    type: 'post',
    url: 'http://127.0.0.1:5500/php/base.php',
    data: $('form').serialize(),
    success: function() {
      alert('Form was submitted.');
      $('.send').addClass('send-up');
      $('.sent').addClass('sent-up');

      setTimeout(function() {
        $('.send').removeClass('send-up');
        $('.sent').removeClass('sent-up');
      }, 2000);
    }
  });

  return false;

});
.form {
  text-align: right;
  font-family: sans-serif;
  background: #000;
  color: #FFF;
  padding: 50px;
}

form {
  text-align: left;
}

form li {
  position: relative;
  margin-bottom: 55px;
  list-style-type: none;
}

.li-firstname,
.li-lastname {
  width: 44%;
  display: inline-block;
}

.li-firstname {
  margin-right: 68px;
}

input,
textarea {
  background: transparent;
  border: 0;
  outline: 0;
  border-bottom: 2px solid #FFF;
  display: block;
  color: #FFF;
  width: 100%;
  padding: 15px 0 15px 30px;
  box-sizing: border-box;
  transition: border-bottom 0.3s ease-in-out;
  resize: none;
}

.label {
  position: absolute;
  right: 0;
  margin-top: 10px;
}

form i {
  position: absolute;
  bottom: 16.5px;
  transition: color 0.3s ease-in-out;
}

.submit {
  outline: 0;
  border: 0;
  color: #FFF;
  padding: 0;
  width: 243px;
  height: 60px;
  cursor: pointer;
  position: relative;
  background: #704DFA;
  border-radius: 50px;
  text-transform: uppercase;
}

.submit span {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  transition: all 0.7s ease-out;
}

.send-up {
  margin-top: -30px;
  opacity: 0;
}

.sent {
  margin-top: 30px;
  opacity: 0;
}

.sent-up {
  margin-top: 0;
  opacity: 1;
}

input:focus,
textarea:focus {
  border-bottom: 2px solid #704DFA;
}

input:focus i,
textarea:focus i {
  color: #704DFA;
}

span.error {
  font-family: sans-serif;
  font-style: italic;
  font-size: 13px;
  color: #704DFA;
  margin-right: 10px;
}

span.error:not(#checkbox-error) {
  float: left;
  margin-right: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.min.js"></script>
<script src="https://kit.fontawesome.com/a671c6b423.js" crossorigin="anonymous"></script>

<div >
  <form id="form">
    <ul>
      <li >
        <input type="text" name="firstname" id="firstname" required>
        <i ></i>
        <label for="firstname" ><span>First Name</span></label>
      </li>
      <li >
        <input type="text" name="lastname" id="lastname" required>
        <label for="lastname" ><span>Last Name</span></label>
      </li>
      <li >
        <input type="email" name="email" id="email" required>
        <i ></i>
        <label for="email" ><span>Email Address</span></label>
      </li>
      <li >
        <input type="text" name="subject" id="subject" required>
        <i ></i>
        <label for="subject" ><span>Subject</span></label>
      </li>
      <li >
        <textarea name="msg" id="msg" wrap="hard" rows="5" maxlength="2000" required></textarea>
        <i ></i>
        <label for="msg" ><span>Job Proposal</span></label>
      </li>
      <li >
        <input type="checkbox" name="checkbox" id="checkbox" required>
        <label for="checkbox">
You want to work with me specifically because you feel my style fits perfectly to your business.
       </label>
      </li>
    </ul>
  </form>

  <button  type="submit" form="form">
     <span >Submit</span>
     <span >Sent</span>
  </button>
</div>

CodePudding user response:

I have managed to solve the problem myself. Being a complete beginner in JS, I am a bit disappointed nobody pointed out such an easy solution. I just needed to move the submission function inside the validation function. Now everything is working perfectly.

// Form Validation & Submission

$(document).ready(function () {

  $("form").validate({

    errorPlacement: function (error, element) {
      $(element)
        .closest("form")
        .find("label[for='"   element.attr("id")   "'] > span")
        .append(error);
    },

    errorElement: "span",

    rules: {
      firstname: "required",
      lastname: "required",
      email: {
        required: true,
        email: true
      },
      subject: "required",
      msg: "required",
      checkbox: "required",
    },

    messages: {
      firstname: "*required",
      lastname: "*required",
      email: {
        required: "*required",
        email: "*invalid email address"
      },
      subject: "*required",
      msg: "*required",
      checkbox: "*required",
    },

    submitHandler: function () {

      var that = $('form'),
        url = that.attr('action'),
        type = that.attr('method'),
        data = {};

      that.find('[name]').each(function (index, value) {
        var that = $(this),
          name = that.attr('name'),
          value = that.val();

        data[name] = value;
      });

      $.ajax({

        url: url,
        type: type,
        data: data,
        success: function (response) {

          console.log(response);
         
          function resetForm () {
            $('form')[0].reset();
          };

          resetForm();

          $('.send').addClass('send-up');
          $('.sent').addClass('sent-up');

          setTimeout(function () {
            $('.send').removeClass('send-up');
            $('.sent').removeClass('sent-up');
          }, 3000);

        }
      });

      return false;

    }
  });

});
.form {
  text-align: right;
  font-family: sans-serif;
  background: #000;
  color: #FFF;
  padding: 50px;
}

form {
  text-align: left;
}

form li {
  position: relative;
  margin-bottom: 55px;
  list-style-type: none;
}

.li-firstname,
.li-lastname {
  width: 44%;
  display: inline-block;
}

.li-firstname {
  margin-right: 68px;
}

input,
textarea {
  background: transparent;
  border: 0;
  outline: 0;
  border-bottom: 2px solid #FFF;
  display: block;
  color: #FFF;
  width: 100%;
  padding: 15px 0 15px 30px;
  box-sizing: border-box;
  transition: border-bottom 0.3s ease-in-out;
  resize: none;
}

.label {
  position: absolute;
  right: 0;
  margin-top: 10px;
}

form i {
  position: absolute;
  bottom: 16.5px;
  transition: color 0.3s ease-in-out;
}

.submit {
  outline: 0;
  border: 0;
  color: #FFF;
  padding: 0;
  width: 243px;
  height: 60px;
  cursor: pointer;
  position: relative;
  background: #704DFA;
  border-radius: 50px;
  text-transform: uppercase;
}

.submit span {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  transition: all 0.7s ease-out;
}

.send-up {
  margin-top: -30px;
  opacity: 0;
}

.sent {
  margin-top: 30px;
  opacity: 0;
}

.sent-up {
  margin-top: 0;
  opacity: 1;
}

input:focus,
textarea:focus {
  border-bottom: 2px solid #704DFA;
}

input:focus i,
textarea:focus i {
  color: #704DFA;
}

span.error {
  font-family: sans-serif;
  font-style: italic;
  font-size: 13px;
  color: #704DFA;
  margin-right: 10px;
}

span.error:not(#checkbox-error) {
  float: left;
  margin-right: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.min.js"></script>
<script src="https://kit.fontawesome.com/a671c6b423.js" crossorigin="anonymous"></script>

<div >
  <form id="form" action="php/base.php" method="post">
    <ul>
      <li >
        <input type="text" name="firstname" id="firstname" required>
        <i ></i>
        <label for="firstname" ><span>First Name</span></label>
      </li>
      <li >
        <input type="text" name="lastname" id="lastname" required>
        <label for="lastname" ><span>Last Name</span></label>
      </li>
      <li >
        <input type="email" name="email" id="email" required>
        <i ></i>
        <label for="email" ><span>Email Address</span></label>
      </li>
      <li >
        <input type="text" name="subject" id="subject" required>
        <i ></i>
        <label for="subject" ><span>Subject</span></label>
      </li>
      <li >
        <textarea name="msg" id="msg" wrap="hard" rows="5" maxlength="2000" required></textarea>
        <i ></i>
        <label for="msg" ><span>Job Proposal</span></label>
      </li>
      <li >
        <input type="checkbox" name="checkbox" id="checkbox" required>
        <label for="checkbox">
You want to work with me specifically because you feel my style fits perfectly to your business.
       </label>
      </li>
    </ul>
  </form>

  <button  type="submit" form="form">
     <span >Submit</span>
     <span >Sent</span>
  </button>
</div>

CodePudding user response:

Your ajax request should look something like this

// try giving an id here
  $('#form').submit(function(){
     
        $.ajax({
            type: 'POST',
            url: 'submit.php', 
            data: $(this).serialize()
        })
        .done(function(data){
             
            // show the response
            $('#result').html('sent');
            document.getElementById("message").value = null;
             
        })
        .fail(function() {
         
            // just in case posting your form failed
            alert( "Posting failed." );
             
        });
 
        // to prevent refreshing the whole page page
        return false;
 
    });

I hope it would work.

  • Related