How to upload a file using AJAX request?

Today, I am going to write solution of a problem I encountered while doing a project. Most of us are familiar with AJAX requests. We send values using ajax request to the server for processing. That's easy right we have been doing that all the time during web development. How about sending an image in the AJAX request? Have you tried that? Yes? Cool. If no, then you are going to learn this today. Yippee. Not only this, you will be able to submit the whole form without hitting submit button and without the page being refreshed. For viewing purpose it might seem like nothing happened at all. But it can turn out a great advantage for you. I used this for to create 'Live Preview' functionality i.e. clicking on a preview button the form was submitted and after successful AJAX request the preview of the submitted values was shown and once the preview is the one we want we can use the save button of the form to save our result. Using the Live Preview won't change anything in our actual data. That just is for preview purpose. You might use it for something else.

Okay so lets get started. Lets create a form. A typical example of a form would be:
<form id="blog_post_form' action="save.php" method="POST" enctype="multipart/form-data">
        <input type="text" id="title" name="title" />
        <textarea id="desc" name="desc" />
        <input type="file" id="image" name="image" />
         <input type="submit" name="submit" id="submit" value="Submit" />
        <span id="presave>PreSave</span>
</form>
<script>
$('#presave').click(function(){    
     var form = new FormData($('#blog_post_form')[0]);  
      $.ajax({
                url: 'pre-save.php',
                type: 'POST',
                mimeType: 'multipart/form-data',              
                success: function (res) {
               
                },            
                data: form,            
                cache: false,
                contentType: false,
                processData: false
            });
});
That's it, now you can submit the Form twice one is by clicking the Submit button and the other is the PreSave button. And you can have two processing pages for the same form. However PreSave can be used only before using the Submit button.

This is possible because of FormData web interface which you can see above. The FormData interface helps us create a clone of the original form. We can even add more fields to the form. Example if we want to add an extra field for presave then we can use append function:
     var form = new FormData($('#blog_post_form')[0]);
     form.append('extra_field','values go here');

Comments

Popular posts from this blog

Automate file upload in Selenium IDE

How To Install and Configure Nextcloud