sending forms through javascript code example
Example 1: javascript ajax post form data
$(document).ready(function() {
// process the form
$('form').submit(function(event) {
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
var formData = {
'name' : $('input[name=name]').val(),
'email' : $('input[name=email]').val(),
'superheroAlias' : $('input[name=superheroAlias]').val()
};
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'process.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
// here we will handle errors and validation messages
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
Example 2: javascript submit a form with id
// 1. Acquire a reference to our <form>.
// This can also be done by setting <form name="blub" id="myAwsomeForm">:
// var form = document.forms.blub;
var form = document.getElementById("myAwsomeForm");
// 2. Get a reference to our preferred element (link/button, see below) and
// add an event listener for the "click" event.
document.getElementById("your-link-or-button-id").addEventListener("click", function () {
form.submit();
});
// 3. any site in your javascript code:
document.getElementById('myAwsomeForm').submit();