Submit Form Without Page Reloading

Submit form without reloading page

You can't do this using forms the normal way. Instead, you want to use AJAX.

A sample function that will submit the data and alert the page response.

function submitForm() {
var http = new XMLHttpRequest();
http.open("POST", "<<whereverTheFormIsGoing>>", true);
http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var params = "search=" + <<get search value>>; // probably use document.getElementById(...).value
http.send(params);
http.onload = function() {
alert(http.responseText);
}
}

How to prevent page from reloading after form submit - JQuery

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

Stop form refreshing page on submit

You can prevent the form from submitting with

$("#prospects_form").submit(function(e) {
e.preventDefault();
});

Of course, in the function, you can check for empty fields, and if anything doesn't look right, e.preventDefault() will stop the submit.

Without jQuery:

var form = document.getElementById("myForm");
function handleForm(event) { event.preventDefault(); }
form.addEventListener('submit', handleForm);

Submit Form Without Reloading Page and Get Output [PHP, jQuery]

To be more specific on my first comment, you have to put an exit statement after you echo the response so the rest of the code doesn't execute, also to check whether the form was sent or not you can add a hidden input in your form with the value "1" (<input name="formSent" type="hidden" value="1">) that gets checked in your PHP :

<?php
if (isset($_POST['formSent'])){
$name=$_POST['name'];
if($name == 'Johny'){
echo "Welcome Johny";
exit;
}
else{
echo "I Dont Know You";
exit;
}
}
?>

and then get the response from the ajax request in the success's callback parameter, also specify the method: 'POST' because jQuery's $.ajax function uses the method GET by default:

<script>
$(function () {

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

e.preventDefault();

$.ajax({
type: 'post',
url: 'on.php',
method: 'POST',
data: $('form').serialize(),
success: function (message) {
alert(message);
}
});

});

});
</script>

Submit form without page reloading

You'll need to submit an ajax request to send the email without reloading the page. Take a look at http://api.jquery.com/jQuery.ajax/

Your code should be something along the lines of:

$('#submit').click(function() {
$.ajax({
url: 'send_email.php',
type: 'POST',
data: {
email: 'email@example.com',
message: 'hello world!'
},
success: function(msg) {
alert('Email Sent');
}
});
});

The form will submit in the background to the send_email.php page which will need to handle the request and send the email.



Related Topics



Leave a reply



Submit