1

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.

Community
  • 1
  • 1
Stefanvp
  • 19
  • 5
  • What exactly do you mean when you say it "stops"? Have you checked for errors in the console? *edit* oh well I guess so because you're using `console.log()`. – Pointy Jan 11 '16 at 16:05
  • And you have no error messages? If you comment out the parse line, does the next console line fire? – epascarello Jan 11 '16 at 16:06
  • I have no errors. That's the confusing part... – Stefanvp Jan 11 '16 at 16:07
  • 3
    Do you get any error messages? JSON.parse should be wrapped in a try-catch block to catch errors on invalid JSON. – arve0 Jan 11 '16 at 16:08
  • A bit more useful than noting: "Unexpected token" ... blank. – Stefanvp Jan 11 '16 at 16:14
  • Possible duplicate of [Uncaught SyntaxError: Unexpected token with JSON.parse](http://stackoverflow.com/questions/14432165/uncaught-syntaxerror-unexpected-token-with-json-parse) – Liam Jan 11 '16 at 16:21
  • Can you do `try { JSON.parse(this.responseText); } catch(e) { console.log(e.message.charCodeAt(17)) }` and see if you get any number in the console? Possibly the character is there, but not printable. – apsillers Jan 11 '16 at 16:22
  • 2
    TL;DR; your Json is invalid, check it on http://jsonlint.com/ – Liam Jan 11 '16 at 16:23
  • @Liam What is invalid about it? jsonlint says it's fine. –  Jan 11 '16 at 16:43
  • Do a `console.log("#"+this.responseText+"#", this.responseText.length)` to see if there’s perhaps any special characters/byte sequences before or after your JSON output. – CBroe Jan 11 '16 at 16:49
  • I'm very confused by this. Why are you consulting `this.responseText` **before** issuing the XHR call? What is `this` anyway? –  Jan 11 '16 at 16:50
  • @apsillers you were absolutely right. I saved the php-file as UTF 8, but with BOM... Tried it without it and it works! Never thought of it. I feel so dumb right now. – Stefanvp Jan 11 '16 at 16:50
  • Can you please format your code. I'm getting a little fed up of doing it for you! – Liam Jan 11 '16 at 16:57

1 Answers1

0

Thanks to @apsillers, I've found the answer. I've saved my url_to_upload_images.php as UTF 8, with bom. This creates an invisible character with the return of the JSON.

Saved it the file as UTF 8 without BOM and it works!

Stefanvp
  • 19
  • 5