How to upload file through Jquery/AJAX

How to upload file through Jquery/AJAX

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

How to upload file through Jquery/AJAX

Uploading files via AJAX is a common requirement, but it introduces specific constraints that standard form submissions do not face. The core issue preventing your current setup from working lies in how jQuery serializes data and how browsers handle multipart requests. When you use $("#createForm").serialize(), jQuery converts the form fields into a URL-encoded string (e.g., name=value&user=john). This format is compatible with simple text inputs but cannot carry binary file data or the necessary boundary strings required by the server to parse the upload.

To get the $_FILES variable populated in your Perl script, you must send the request as multipart/form-data. If you attempt to serialize a form containing an <input type="file"> using jQuery's default method, the file data is stripped out entirely, and the browser sends nothing for that field. The solution involves constructing the payload manually or configuring jQuery to handle the boundary logic automatically.

Preparing the File Input

First, ensure your HTML form includes a proper file input element with a specific name attribute. In your existing code, you are sending data as $("#createForm").serialize(). You need to isolate the text fields and the file field, treating them differently during the AJAX call.

Add an <input type="file" name="avatar"> (or whatever name your backend expects) to your form. Crucially, do not let jQuery serialize this input into the query string. Instead, you will construct a FormData object. This object acts as a bridge, allowing you to append standard fields and binary files without needing to manually calculate boundary strings or encode the data.

Implementing FormData in AJAX

Replace your current .serialize() call with a FormData object. Here is how you modify the client-side JavaScript:

$(document).ready(function(){
    $("form#createForm").submit(function(event) {
        event.preventDefault(); // Prevent default form submission to handle via AJAX

        var formData = new FormData($("#createForm")[0]);

        // Disable submit button and save TinyMCE state
        $("form#createForm input#createForm_submit").attr('disabled', 'disabled');
        tinyMCE.triggerSave();

        $.ajax({
            url: "perform", 
            type: "POST",
            data: formData, // Pass the FormData object directly
            processData: false, // jQuery must not process (serialize) this data
            contentType: false, // Let browser set content-type to multipart/form-data
            dataType: 'json',

            success: function(data){
                $('div.form-group').each(function(){
                    $(this).removeClass('has-error');
                });

                if (data.error) {
                    var myList = $('ul.msg-list').empty();
                    $.each(data.msg, function(key, item) {
                        $("div."+key).addClass('has-error');
                        $('li').text(item.errtxt).appendTo(myList); // Corrected selector usage
                    });
                    $('div#create_createresult').html('').append(myList);
                    $('div#create_createresult').addClass("text-danger");
                } else {
                    $('div#create_createresult').text(data.msg);
                    $('div#create_createresult').addClass("success");
                }

                $("form#createForm input#createForm_submit").removeAttr('disabled');
            },
            error: function(xhr, status, error) {
                // Handle network or server errors gracefully
                console.log(error);
                $("form#createForm input#createForm_submit").removeAttr('disabled');
            }
        });

        return false;
    });
});

Key Configuration Details

Two specific flags in the AJAX configuration are non-negotiable for file uploads: processData: false and contentType: false. When these are set to default (true), jQuery attempts to serialize the data into a URL-encoded string and sets the Content-Type header to application/x-www-form-urlencoded. This explicitly breaks the multipart format required for files. By disabling these settings, you allow the browser to handle the encoding of the file boundaries and the setting of the correct Content-Type header automatically.

Server-Side Expectations

On the server side (your Perl script), receiving a request with this configuration will result in the $_FILES superglobal being populated correctly. You can access the uploaded image via $_FILES['avatar'] (matching the name of your input). Ensure your backend logic is prepared to handle the binary data associated with that array key, as standard form parsing functions will not work on multipart payloads.

If you are looking for a modern PHP stack to handle this complexity more robustly, Laravel provides excellent file upload handling utilities. For instance, LaravelCompany offers resources on how to manage uploads within their ecosystem, but understanding the underlying FormData mechanism remains essential regardless of the framework chosen.

Our network