Sunday, May 19, 2024
51
rated 0 times [  53] [ 2]  / answers: 1 / hits: 19455  / 11 Years ago, sun, december 22, 2013, 12:00:00

I'm trying to send a multipart/form-data content-type request:



var xhr = new XMLHttpRequest();

xhr.onreadystatechange = function(){
if(xhr.readyState==4){
alert(xhr.responseText);
}
}

xhr.open(POST, url, true);
xhr.setRequestHeader(Content-Type,multipart/form-data; boundary=---------------------------275932272513031);

xhr.send('-----------------------------275932272513031 Content-Disposition: form-data; name=name

test

----------------------------275932272513031--');


Then in php I just print the $_POST array



print_r($_POST);


But I get an empty array each time. I expect to see



Array (
name => test
)


What am I doing wrong?


More From » xmlhttprequest

 Answers
14

Your code failed because you've used Enter instead of an escaped line break character (n).

JavaScript doesn't support first line[Enter]second line. If you need a string with a line break, use first linensecond line.



Once you've fixed this problem, your code should work as intended (with one caveat, see final note):





var xhr = new XMLHttpRequest();
xhr.onload = function() {
alert(xhr.responseText);
};
xhr.open(POST, url, true);
xhr.setRequestHeader(Content-Type,multipart/form-data; boundary=---------------------------275932272513031);
xhr.send('-----------------------------275932272513031n' +
'Content-Disposition: form-data; name=namenn' +
'testnn' +
'----------------------------275932272513031--');


NOTE: Your code will only work for payloads that consists of UTF-8 characters, not binary data. If you want to learn more about submitting forms with binary data via XMLHttpRequest, see this answer and its linked references.


[#73599] Friday, December 20, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ulysses

Total Points: 111
Total Questions: 118
Total Answers: 113

Location: Zambia
Member since Sat, Oct 31, 2020
4 Years ago
;