Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
  • Submit form data in Ajax

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 550
    Comment on it

    We will learn here, how we can submit form data with the help of Ajax.

    First step:-

    Create index.html file and create a form with the three labels/fields:- Name,Email and Superhero Alias. Inside head tag we have included one css file and two scripts file i.e bootstrap.min.css, jquery.min.js and magic.js

    Let us look into these files:-

    bootstrap.min.css:- is css file which includes the code for responsive design,look and feel.

    jquery.min.js:- It is script file a Jquery Library, which is must to include inside head tag to make Ajax code run.

    magic.js:- It is script file in which we have written the Ajax code to process form data.

    <!doctype html>
        <title>Submit form data in Ajax</title>
        <link rel="stylesheet" href="//"> <!-- load bootstrap via CDN -->
        <script src="//"></script> <!-- load jquery via CDN -->
        <script src="magic.js"></script> <!-- load our javascript file -->
    <div class="col-sm-6 col-sm-offset-3">
        <h1>Processing an AJAX Form</h1>
        <!-- OUR FORM -->
        <form action="process.php" method="POST">
            <!-- NAME -->
            <div id="name-group" class="form-group">
                <label for="name">Name</label>
                <input type="text" class="form-control" name="name" placeholder="Your Name">
                <!-- errors will go here -->
            <!-- EMAIL -->
            <div id="email-group" class="form-group">
                <label for="email">Email</label>
                <input type="text" class="form-control" name="email" placeholder="">
                <!-- errors will go here -->
            <!-- SUPERHERO ALIAS -->
            <div id="superhero-group" class="form-group">
                <label for="superheroAlias">Superhero Alias</label>
                <input type="text" class="form-control" name="superheroAlias" placeholder="Ant Man">
                <!-- errors will go here -->
            <button type="submit" class="btn btn-success">Submit <span class="fa fa-arrow-right"></span></button>

    Second Step:-

    Create a magic.js or any file you wish to create and we will write a Ajax code in it.

    Note:- Make sure whatever file you will create , that file should be include inside head tag in index.html file.

    // magic.js
    $(document).ready(function() {
        // process the form
        $('form').submit(function(event) {
            $('.form-group').removeClass('has-error'); // remove the error class
            $('.help-block').remove(); // remove the error text
            // 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
                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
                    // here we will handle errors and validation messages
                    if ( ! data.success) {
                        // handle errors for name ---------------
                        if ( {
                            $('#name-group').addClass('has-error'); // add the error class to show red input
                            $('#name-group').append('<div class="help-block">' + + '</div>'); // add the actual error message under our input
                        // handle errors for email ---------------
                        if ( {
                            $('#email-group').addClass('has-error'); // add the error class to show red input
                            $('#email-group').append('<div class="help-block">' + + '</div>'); // add the actual error message under our input
                        // handle errors for superhero alias ---------------
                        if (data.errors.superheroAlias) {
                            $('#superhero-group').addClass('has-error'); // add the error class to show red input
                            $('#superhero-group').append('<div class="help-block">' + data.errors.superheroAlias + '</div>'); // add the actual error message under our input
                    } else {
                        // ALL GOOD! just show the success message!
                        $('form').append('<div class="alert alert-success">' + data.message + '</div>');
                        // usually after form submission, you'll want to redirect
                        // window.location = '/thank-you'; // redirect a user to another page
                // using the fail promise callback
                .fail(function(data) {
                    // show any errors
                    // best to remove for production
            // stop the form from submitting the normal way and refreshing the page

    Let us try to understand Ajax code

    All Ajax code is written inside $(document).ready(function() { --- } . It means when we click on the submit button, document which is our index file will call ready inbuilt jquery function. Now it will run the code line by line written inside it. Some jquery functions are in use in this code. To learn each and every functions, Please refer

    Third Step:-

    Create process.php file, process.php file will process data in php after submitting data through Ajax in index.html

    $errors         = array();      // array to hold validation errors
    $data         = array();      // array to pass back data
    // validate the variables ======================================================
        // if any of these variables don't exist, add an error to our $errors array
        if (empty($_POST['name']))
            $errors['name'] = 'Name is required.';
        if (empty($_POST['email']))
            $errors['email'] = 'Email is required.';
        if (empty($_POST['superheroAlias']))
            $errors['superheroAlias'] = 'Superhero alias is required.';
    // return a response ===========================================================
        // if there are any errors in our errors array, return a success boolean of false
        if ( ! empty($errors)) {
            // if there are items in our errors array, return those errors
            $data['success'] = false;
            $data['errors']  = $errors;
        } else {
            // if there are no errors process our form, then return a message
            // show a message of success and provide a true success variable
            $data['success'] = true;
            $data['message'] = 'Success!';
        // return all our data to an AJAX call
        echo json_encode($data);

    process.php file will give response to Ajax function in Json


 0 Comment(s)

Sign In

Sign up using

Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: