Last Updated:

jQuery : Upload all form fields to the server using ajax

jQuery

Transfer all data from the form to the server using ajax.

Passing all form fields using jQuery and ajax is easy enough.

  1. First, let's connect the jQuery library.
    <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
  2. Let's create a form from two fields (Name and email).
    <form method="POST" id="form">
         <legend>Example of passing all form fields</legend>
         <div>
             <label for="name">Name:</label>
             <input id="name" name="name" value="" type="text">
         </div>
         <div>
             <label for="email">Email address:</label>
             <input id="email" name="email" value="" type="email">
         </div>
         <input id="send" value="Submit" type="submit">
    </form>
  3. Write code that conveys the entire state of the form in a serialized form (including all the fields inside the form).

    When you click on the send button, the values of all form fields with id="form" will be passed.

The variable serializeFormData takes serialized form data - $('#form').serialize() and passes it to the server (in the example, url - url: '/get-form-data').
<script type="text/javascript" language="javascript">
     $('#send').click(function() {
         var serializeFormData = $('#form').serialize();
        
         $.ajax({
           type: 'POST',
           url: '/get-form-data',
           data: serializeFormData,
           success: function(data) {
               console log(data);
           },
           error: function(data){
               console.log('Warning! an error occurred:' + data);
           }
         });
     });
</script>


Next, on the server side, we receive and see the received data.

Result:
var_dump($_POST);

Array
(
[name] => fixlix
[email] => test@mail.com

)