I'm trying to make a drag and drop upload field with a tutorial from codecourse/phpacademy, but after several hours of trying and figuring out why I'm not getting what I expected, I went to bed to try it the next day.
It is two days later and I am lost.
I am trying to create a div where a user can drop multiple images, which are immediately uploaded to the server. The server response should be a JSON-string containing one or more arrays with a name and a path for the uploaded file. This JSON string is then used to display the file's name on the upload page.
What is working:
- I can drag and drop my image onto the div and the element changes style
- The files are uploaded
- I'm receiving a JSON-string back from the server
What isn't working:
- displaying file names above the dropzone-div
By the looks of this, stops my javascript without an error message by the line where JSON.parse receives its contents. EDIT: I am receiving an error, thanks to arve0, "Unexpected token", but with no token showing.
var upload = function(files) {
var formData = new FormData(),
xhr = new XMLHttpRequest(),
x;
for(x = 0; x < files.length; x = x + 1) {
formData.append('files[]', files[x]);
}
try {
console.log("DING!1");
console.log(this.responseText);
var data = JSON.parse(this.responseText);
console.log("DING!2");
displayUploads(data);
console.log("DING!3");
} catch(e) {
alert(e); //error in the above string(in this case,yes)!
}
xhr.open('post', 'url_to_upload_images.php?uniqueParamVal=' + new Date().getTime(), true);
xhr.send(formData);
};
The console shows:
DING!1
[{"name":"1452525771.jpg","file":"..\/folder_with_images\/1452525771.jpg"}]
typeof this.responseText is string.
It's all located on the same domain.
Error: "Unexpected token", no token showing...
Is there a problem with my code? If so, what is a possible solution? If not, what can I use to get the same result I wanted?
TL;DR:
Javascript stops on JSON.parse(this.responseText)
in XMLHttpRequest.onload
typeof this.responseText is string.
It's all located on the same domain.
Error: "Unexpected token", no token showing...
Edit about duplicate of Uncaught SyntaxError: Unexpected token with JSON.parse
I've read the answers given, but it is still not working.
-JSON.parse()
can only accept a string.
=typeof this.responseText
is string.
JSON.stringify(this.response);
doesn't work either.
-New-line characters, tabs and backslashes make it invalid.
=I've run my JSON string trough a validator and it was valid JSON. But to be sure, I've removed all backslashes. Actually, I've commented out some PHP.
if (move_uploaded_file($_FILES["files"]["tmp_name"][$position], $target_file)) {
$uploaded[] = array(
'name' => time().".".$imageFileType//,
//'file' => $target_file
);
}
Returning: [{"name":"1452529278.jpg"}]
but it was still containing an unexpected token.