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:
- Use
<button type="button">
to override default submission behavior - 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
How to Change an Element'S Text Without Changing Its Child Elements
Is There a Spec That the Id of Elements Should Be Made Global Variable
Resizing an Image in an Html5 Canvas
Where to Place JavaScript in an HTML File
Get Dom Content of Cross-Domain Iframe
How to Hide the Html5 Number Input'S Spin Box
Onclick to Get the Id of the Clicked Button
Submit Two Forms With One Button
How to Get an HTML Element'S Style Values in JavaScript
Load and Execution Sequence of a Web Page
What Does "./" (Dot Slash) Refer to in Terms of an HTML File Path Location
Detecting Input Change in Jquery
Using an HTML Button to Call a JavaScript Function
Get File Size, Image Width and Height Before Upload
How to Call Multiple JavaScript Functions in Onclick Event
Why Js Function Name Conflicts With Element Id
Jquery Document.Createelement Equivalent
Twitter Bootstrap Tabs: Go to Specific Tab on Page Reload or Hyperlink