empty $_POST while sending Blob - javascript

I'm sending binary data to server using Blob, but there is nothing in $_POST variable. What did I do wrong?
var xhr = new XMLHttpRequest();
xhr.open('POST', '/save.php', true);
var formData = new FormData();
formData.append("data", new Blob(["㚂☇䰉耸ڀ찃怮...binary...:⡒㠯ݟᑣ"]));
xhr.send(formData);
xhr.onload = function(e){
if (this.status == 200){
console.log(this.responseText);
}
};
server side:
var_dump($_POST); //returns array(0) {}

This is a really simple fix...
When you send a BLOB it sends as a file not as post data. Therefore you need to use $_FILES not $_POST.
Using your code modified to var_dump($_FILES) outputs:
"array(1) {
["data"]=>
array(5) {
["name"]=>
string(4) "blob"
["type"]=>
string(24) "application/octet-stream"
["tmp_name"]=>
string(14) "/tmp/tmpfilename"
["error"]=>
int(0)
["size"]=>
int(44)
}
}
You could then open the file serverside with file_get_contents($_FILES['data']['tmpname']) same as you would any other uploaded file.

I managed to send that data this way:
var xhr = new XMLHttpRequest();
xhr.open('POST', '/save.php', true);
xhr.send("㚂☇䰉耸ڀ찃怮...binary...:⡒㠯ݟᑣ");
xhr.onload = function(e){
if (this.status == 200){
console.log(this.responseText);
}
};
server side:
var_dump($HTTP_RAW_POST_DATA); //string(1820) "㚂☇䰉耸ڀ찃怮...binary...:⡒㠯ݟᑣ"

Related

.obj files not sending xhr post

I have a jquery code where I send files with xhr post, this code works fine for other files but for files with ".obj" extension it doesn't send any value in post (it doesn't send test data independent of the file either)
When I print the file value to the console, I can see that it is written correctly
Code;
var form = new FormData();
form.append("file", file);
form.append("test", "test");
var xhr = new XMLHttpRequest();
xhr.open("POST", "desk.php", true);
xhr.onload = function ()
{
if (xhr.status == 200)
{
var response = JSON.parse(xhr.responseText);
console.log(response);
}
};
xhr.send(form);

Sending FormData to PHP file not working as expected

I have a XMLHttpRequest to send a courseName to php file on the server like this:
const xhr = new XMLHttpRequest();
xhr.onload = function(e) {
if(this.readyState === 4) {
console.log("Server returned: ",e.target.responseText);
}
};
const fd = new FormData();
fd.append("courseName", 'Math');
xhr.open("POST", "upload.php", true);
xhr.send(fd);
PHP:
<?php
echo $_FILES['courseName']
?>
But nothing is returned, I'm confused please help... it should return Math, Doesn't it?
The network doesn't show any data sent over.
How to use FormData for AJAX file upload?
Shows you how to send files using FormData ...
Best,
Smith

AttributeError: 'NoneType' object has no attribute 'get' //500 (Internal Server Error)

this is not sending any data from crome extension,i am trying to send json string to the server with mentioned url which says none type object has been returned,
var xhr = new XMLHttpRequest();
var ur = "http://127.0.0.1:8080/animal";
var dat = {"subject":"subject"};
xhr.open("POST", ur, true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
// do something with response
console.log(xhr.responseText);
}
};
xhr.send(dat);
}
};
xhr.send(dat);
You can't send an object with xhr.send(), you need to serialize it.
var dat = 'subject=subject';

How to pass base64encode string through XMLHttpRequest() post request

I am trying to upload a image to server,In that i have converted image to base64encode string and i need to pass that base64encode string to webservice,that webservice convert the base64 string to file and saving in database.but base64encode string has huge length approximately(85,000) when i pass this string to webservice i am getting the following error.
Failed to load resource: the server responded with a status of 400 (Bad Request)
i need to pass this by using only XMLHttpRequest() with out using the ajax,jquery please help me.
below is my code.
var filesToBeUploaded = document.getElementById("afile");
var file = filesToBeUploaded.files[0];
var reader = new FileReader();
reader.onload = function(event) {
var binaryStringResult = reader.result;
var binaryString =binaryStringResult.split(',')[1];
var xhr = new XMLHttpRequest();
xhr.open("POST","http://url/api/jsonws/Global-portlet.org_roles/add-file-entry?repositoryId=11304&folderId=0&sourceFileName=test108.jpeg&mimeType=image%2Fjpeg&title=test108.jpeg&description=test108.jpeg&changeLog=test108.jpeg&basecode64="+ binaryString);
xhr.setRequestHeader("Authorization","BasicbmFyYXlhbmFAdmlkeWF5dWcuY29tOnRlc3Q=");
xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xhr.send();
xhr.onload = function() {
alert('in sucess');
};
xhr.onerror = function(e) {
alert('in error');
};
}
reader.readAsDataURL(file);
For POST, don't include it in the URL, you need to put it in the body, i.e.
xhr.send(binaryString);
I doubt your Content-Type of application/x-www-form-urlencoded is correct in this case.
I think the issue that you encountering here is that you are exceeding the maximum length of a query string.
What you need to do is something like the following:
var xhr = new XMLHttpRequest();
var url = "http://url/api/jsonws/Global-portlet.org_roles/add-file-entry";
var params = "repositoryId=11304&folderId=0&sourceFileName=test108.jpeg&mimeType=image%2Fjpeg&title=test108.jpeg&description=test108.jpeg&changeLog=test108.jpeg&basecode64="+ binaryString;
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Content-length", params.length);
xhr.setRequestHeader("Connection", "close");
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
}
xhr.send(params);
Hope that helps

XMLHttpRequest returns wrongly encoded characters

I use XMLHttpRequest to read the PDF document
http://www.virtualmechanics.com/support/tutorials-spinner/Simple2.pdf
%PDF-1.3
%âãÏÓ
[...]
and print its content out to console:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
console.log('âãÏÓ');
}
};
xhr.open('GET', 'http://www.virtualmechanics.com/support/tutorials-spinner/Simple2.pdf', true);
xhr.send();
However, the console says
%PDF-1.3
%����
[...]
âãÏÓ
(The last line is from the reference console.log above to verify that the console can actually display those characters.)
Apparently, the characters are wrongly encoded at some point. What's going wrong and how to fix this?
XMLHttpRequest's default response type is text, but here one is actually dealing with binary data. Eric Bidelman describes how to work with it.
The solution to the problem is to read the data as a Blob, then to extract the data from the blob and plug it into hash.update(..., 'binary'):
var xhr = new XMLHttpRequest();
xhr.open('GET', details.url, true);
xhr.responseType = 'blob';
xhr.onload = function() {
if (this.status === 200) {
var a = new FileReader();
a.readAsBinaryString(this.response);
a.onloadend = function() {
var hash = crypto.createHash('sha1');
hash.update(a.result, 'binary');
console.log(hash.digest('hex'));
};
}
};
xhr.send(null);
The MIME type of your file might not be UTF-8. Try overriding it as suggested here and depicted below:
xhr.open('GET', 'http://www.virtualmechanics.com/support/tutorials-spinner/Simple2.pdf', true);
xhr.overrideMimeType('text/xml; charset=iso-8859-1');
xhr.send();

Categories