Uploading a file with ajax serialize() does not work?

This was driving me nuts as I often use Ajax to save different data without refreshing the page, however when I tried to use it for a multipart form when uploading an image, it would not work.

After a bit of searching I found this solution which worked for me.

The form:

<form class="form-inline" id="imageUpload" enctype="multipart/form-data">
    <div class="form-group" >
        <label for="file">Select image to upload:</label>
        <input type="file" name="file" id="file" >
     </div>
     <button type="submit" class="btn btn-primary">Upload Image</button>
</form>

The ajax:

<script type="text/javascript">
    $(document).ready(function() {
        $("#imageUpload").submit(function(e) {
            e.preventDefault();

            var formData = new FormData(this);

            $.ajax({
                type: "POST",
                data: formData,
                cache:false,
                contentType: false,
                processData: false,
                url: "/activity/add/photo",
                dataType: "json",
                success: function(data) {
                    $('#imagedisplay').html(data.name);
                },
                error: function() {
                    $('#imageerror').html('data.file');         
                }
            });
        });
    });
</script>

 

2 thoughts on “Uploading a file with ajax serialize() does not work?”

  1. From this code, how can i do for the upload of the image into database, i did “insert INTO with the value of $_POST[‘file’]” , but it not working. How can i resolve?

  2. Uploading to the database is beyond the scope of this article. I will look at adding an article about the code you need to add a database entry in the future. Try Stackoverflow for a solution to your issue as you can post all your code there which helps a lot to solve issues like yours. Good luck.

Leave a Reply

Your email address will not be published. Required fields are marked *