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
    • 639
    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.

    1. <!doctype html>
    2. <html>
    3. <head>
    4. <title>Submit form data in Ajax</title>
    5. <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css"> <!-- load bootstrap via CDN -->
    6. <script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> <!-- load jquery via CDN -->
    7. <script src="magic.js"></script> <!-- load our javascript file -->
    8. </head>
    9. <body>
    10. <div class="col-sm-6 col-sm-offset-3">
    11.  
    12. <h1>Processing an AJAX Form</h1>
    13.  
    14. <!-- OUR FORM -->
    15. <form action="process.php" method="POST">
    16.  
    17. <!-- NAME -->
    18. <div id="name-group" class="form-group">
    19. <label for="name">Name</label>
    20. <input type="text" class="form-control" name="name" placeholder="Your Name">
    21. <!-- errors will go here -->
    22. </div>
    23.  
    24. <!-- EMAIL -->
    25. <div id="email-group" class="form-group">
    26. <label for="email">Email</label>
    27. <input type="text" class="form-control" name="email" placeholder="youremail@gmail.com">
    28. <!-- errors will go here -->
    29. </div>
    30.  
    31. <!-- SUPERHERO ALIAS -->
    32. <div id="superhero-group" class="form-group">
    33. <label for="superheroAlias">Superhero Alias</label>
    34. <input type="text" class="form-control" name="superheroAlias" placeholder="Ant Man">
    35. <!-- errors will go here -->
    36. </div>
    37.  
    38. <button type="submit" class="btn btn-success">Submit <span class="fa fa-arrow-right"></span></button>
    39.  
    40. </form>

    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.

    1. // magic.js
    2. $(document).ready(function() {
    3.  
    4. // process the form
    5. $('form').submit(function(event) {
    6.  
    7. $('.form-group').removeClass('has-error'); // remove the error class
    8. $('.help-block').remove(); // remove the error text
    9.  
    10. // get the form data
    11. // there are many ways to get this data using jQuery (you can use the class or id also)
    12. var formData = {
    13. 'name' : $('input[name=name]').val(),
    14. 'email' : $('input[name=email]').val(),
    15. 'superheroAlias' : $('input[name=superheroAlias]').val()
    16. };
    17.  
    18. // process the form
    19. $.ajax({
    20. type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
    21. url : 'process.php', // the url where we want to POST
    22. data : formData, // our data object
    23. dataType : 'json', // what type of data do we expect back from the server
    24. encode : true
    25. })
    26. // using the done promise callback
    27. .done(function(data) {
    28.  
    29. // log data to the console so we can see
    30. console.log(data);
    31.  
    32. // here we will handle errors and validation messages
    33. if ( ! data.success) {
    34.  
    35. // handle errors for name ---------------
    36. if (data.errors.name) {
    37. $('#name-group').addClass('has-error'); // add the error class to show red input
    38. $('#name-group').append('<div class="help-block">' + data.errors.name + '</div>'); // add the actual error message under our input
    39. }
    40.  
    41. // handle errors for email ---------------
    42. if (data.errors.email) {
    43. $('#email-group').addClass('has-error'); // add the error class to show red input
    44. $('#email-group').append('<div class="help-block">' + data.errors.email + '</div>'); // add the actual error message under our input
    45. }
    46.  
    47. // handle errors for superhero alias ---------------
    48. if (data.errors.superheroAlias) {
    49. $('#superhero-group').addClass('has-error'); // add the error class to show red input
    50. $('#superhero-group').append('<div class="help-block">' + data.errors.superheroAlias + '</div>'); // add the actual error message under our input
    51. }
    52.  
    53. } else {
    54.  
    55. // ALL GOOD! just show the success message!
    56. $('form').append('<div class="alert alert-success">' + data.message + '</div>');
    57.  
    58. // usually after form submission, you'll want to redirect
    59. // window.location = '/thank-you'; // redirect a user to another page
    60.  
    61. }
    62. })
    63.  
    64. // using the fail promise callback
    65. .fail(function(data) {
    66.  
    67. // show any errors
    68. // best to remove for production
    69. console.log(data);
    70. });
    71.  
    72. // stop the form from submitting the normal way and refreshing the page
    73. event.preventDefault();
    74. });
    75.  
    76. });

    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 https://api.jquery.com

    Third Step:-

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

    1. <?php
    2.  
    3. $errors = array(); // array to hold validation errors
    4. $data = array(); // array to pass back data
    5.  
    6. // validate the variables ======================================================
    7. // if any of these variables don't exist, add an error to our $errors array
    8.  
    9. if (empty($_POST['name']))
    10. $errors['name'] = 'Name is required.';
    11.  
    12. if (empty($_POST['email']))
    13. $errors['email'] = 'Email is required.';
    14.  
    15. if (empty($_POST['superheroAlias']))
    16. $errors['superheroAlias'] = 'Superhero alias is required.';
    17.  
    18. // return a response ===========================================================
    19.  
    20. // if there are any errors in our errors array, return a success boolean of false
    21. if ( ! empty($errors)) {
    22.  
    23. // if there are items in our errors array, return those errors
    24. $data['success'] = false;
    25. $data['errors'] = $errors;
    26. } else {
    27.  
    28. // if there are no errors process our form, then return a message
    29.  
    30. // DO ALL YOUR FORM PROCESSING HERE
    31. // THIS CAN BE WHATEVER YOU WANT TO DO (LOGIN, SAVE, UPDATE, WHATEVER)
    32.  
    33. // show a message of success and provide a true success variable
    34. $data['success'] = true;
    35. $data['message'] = 'Success!';
    36. }
    37.  
    38. // return all our data to an AJAX call
    39. echo json_encode($data);

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

    Thanks

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Reset Password
Fill out the form below and reset your password: