Search code examples
javascriptajaxformsxmlhttprequest

formData is empty (while uploading it through XMLHttpRequest - pure javascript)


I need to send along with my variable data also a blob file, so i needed to switch from POST plain

 http1.send("var1=" + var1 + "&var2=" + var2 + "")

to formData.

But formData is totally empty, even when I output it to the console. Here's my code.

var formData = new FormData();
formData.append("customer_id", customer_id)
formData.append("nume", btoa(nume))
formData.append("prenume", btoa(prenume))
formData.append("signature", blob, "signature.jpg");
.....

var phpscript = 'AJAX/ajax_save_form.php'
http1.open('POST', phpscript)
http1.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
http1.onreadystatechange = function()
{
    if(http1.readyState == 4)
    {
        if(http1.status == 200)
        {
            var ajaxMessage = http1.responseText    
            alert(ajaxMessage)

        } 
    }
}
http1.send(formData);

console.log(formData);

Here are some typical values for my variables :

customer_id = 4
nume = 'Bill'
prenume = 'Gates'
blob = .jpeg file

Can anyone track this for me ? Where am I wrong ? I browsed the net for 20 different solutions and pages, and none can solve my problem.

Thanks !!!


Solution

  • The FormData object needs to be sent as multipart/form-data, you set the content type as application/x-www-form-urlencoded.
    Remove the call to setRequestHeader and the correct content type will be set.