Uploading Image with Formdata

Submit Form with files using XHR

For posting a form using ajax with files, $.post will never work to make it possible we have to use XMLHttpRequest.


    $("#footer").html("Creating.");
    var formElement = document.querySelector('#form'),
        fileInput = document.querySelector('#logo'),
        xhr = new XMLHttpRequest();

    xhr.open('POST', '/upload/index.php');

    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) {
            var response = jQuery.parseJSON(xhr.response);
            alert(response);
            
        } else {
            $("#footer").html("Connection Failed! Not Saved.");
        }
    }

    var form = new FormData(formElement);
    $("#footer").html("Creating...");
    xhr.send(form);

Here we are sending form data to upload/index.php which will pickup and save image on server.