formData object not working with jquery AJAX post?

╄→гoц情女王★ 提交于 2019-12-03 02:21:58

When you're sending an ajax request via jQuery and you want to send FormData you don't need to use JSON.stringify on this FormData. Also when you're sending file the content type must be multipart/form-data including boundry - something like this multipart/form-data; boundary=----WebKitFormBoundary0BPm0koKA

So to send FormData including some file via jQuery ajax you need to:

  • Set data to the FormData without any modifications.
  • Set processData to false (Lets you prevent jQuery from automatically transforming the data into a query string).
  • Set the contentType to false (This is needed because otherwise jQuery will set it incorrectly).

Your request should look like this:

var formData = new FormData();

formData.append('name', dogName);
// ... 
formData.append('file', document.getElementById("dogImg").files[0]);


$.ajax({
    type: "POST",
    url: "/foodoo/index.php?method=insertNewDog",
    data: formData,
    processData: false,
    contentType: false,
    success: function(response) {
        console.log(response);
    },
    error: function(errResponse) {
        console.log(errResponse);
    }
});

if you did exactly as pervious anwswer and still not working dont worry its working

maybe intelligence and quick wath are telling you its not working

but dont worry, look at network tap

its working

hope this saves your time

//For those who use plain javascript

var form = document.getElementById('registration-form'); //id of form
var formdata = new FormData(form);
var xhr = new XMLHttpRequest();
xhr.open('POST','form.php',true);
// xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); 
//if you have included the setRequestHeader remove that line as you need the 
// multipart/form-data as content type.
xhr.onload = function(){
 console.log(xhr.responseText);
}
xhr.send(formdata);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!