ajax send form data code example

Example 1: how to send data using ajax

$.ajax({
	url: "/something", // the url we want to send and get data from
    type: "GET", // type of the data we send (POST/GET)
    data: {p1: "This is our data"}, // the data we want to send
    success: function(data){ // when successfully sent data and returned
    	// do something with the returned data
   		console.log(data);
    }
}).done(function(){
	// this part will run when we send and return successfully
    console.log("Success.");
}).fail(function(){
    // this part will run when an error occurres
    console.log("An error has occurred.");
}).always(function(){
    // this part will always run no matter what
  	console.log("Complete.");
});

Example 2: 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 3: ajax submit form data

$(function() {
  $('form.my_form').submit(function(event) {
    event.preventDefault(); // Prevent the form from submitting via the browser
    var form = $(this);
    $.ajax({
      type: form.attr('method'),
      url: form.attr('action'),
      data: form.serialize()
    }).done(function(data) {
      // Optionally alert the user of success here...
    }).fail(function(data) {
      // Optionally alert the user of an error here...
    });
  });
});