0

So I am using AJAX to upload an image with this image manager tool I am building... all of a sudden its not working... I didn't change any code or anything.

The .php runs and uploads the image, but the events I want to fire after the json is encoded and sent back arent happening. :/

The console logs Uncaught SyntaxError: Unexpected token <

The same things is happening on another AJAX request, but is fine on the third one...

In the past when I get this error, it is a PHP syntax error, but I have not updated the .php in a while.. soooo Im stumped.

Here is my Javascript:

$("#chosenfile").change(function(){

    if($(this).attr('name')) {

        var data;

        data = new FormData();
        data.append('uploadedfile', $( '#chosenfile' )[0].files[0]);
        $('#loader').css('display','block');
        $.ajax({
            url: '/includes/uploadimage.php',
            data: data,
            processData: false,
            contentType: false,
            type: 'POST',
            success: function ( data ) {
                //console.log(data); //returns a string of the data.
                var image = JSON.parse(data); //parses the string into an object.
                console.log(image); //logs the object.
                if (image.error) {
                    alert(image.error);
                    $('#remove').click();
                    $('#loader').css('display','none');
                } else {
                    if (image.link) { //If the image is uploaded and returned a link.
                        $('#remove').click();
                        $('#loader').css('display','none');
                        $('#scrollwindow').append("<div class='you'><img imgid='" + image.id + "' src='" + image.link + "' alt=''><span class='delete'>x</span></div>").fadeIn(200);
                        addToSlider(1);
                    };
                }
            }
        }); 

    }

});

Here is my PHP:

<?php

include '../includes/global.php'; // General Vars and Functions I use sitewide.

/* ------------------------- */
/* -- Lets Get that file! -- */
/* ------------------------- */

    $file = $_FILES["uploadedfile"];

    $Return = array();
    $status = "failure";

/* ------------------------- */
/* - Okay, lets upload it! - */
/* ------------------------- */


    $Return["type"] = $file["type"];

    $target_path = "../uploads/"; // Define a folder to upload to

    $allowedExts = array("jpeg", "jpg", "JPG", "JPEG", "image/jpg"); // Array of allowed extensions.
    $extension = end(explode("/", $file["type"])); // Find extension.
    $maxsize = 2097152; // Get Max file size from hidden field in form.

    if ($file) {
        if (in_array($extension, $allowedExts)) // If the extension is allowed.
        {

            if(($file["size"] < $maxsize)) { // If size is less then max file size.

                $uploadResponse = "The file is a good size - ";

                $target_path = $target_path . basename($file['name']);  //Add file name string to upload folder destination string.
                $imageLink = "http://scoutsamerica.com/uploads/" . basename( $file['name']); // This is the full link

                if (file_exists($target_path)) { // If that file already exists, add a random integer to the end of it after a "_".

                    $uploadResponse .=  "This file exists: " . $target_path;

                    $randomNum = rand(1, 9999999);
                    $crudparts = explode(".", $file["name"]); //split filename and extension again.
                    $exceptExt =  $crudparts[0]; //Filename
                    $extension =  $crudparts[1]; //Extension
                    $target_path = "../uploads/" . $exceptExt . "_" . $randomNum . "." . $extension; //rename it with the random number.
                    $imageLink = "http://scoutsamerica.com/uploads/"  . $exceptExt . "_" . $randomNum . "." . $extension;

                    $uploadResponse .= " Path changed to: " . $target_path;
                }

                if(move_uploaded_file($file['tmp_name'], $target_path)) {
                        $uploadResponse .= "The file ".  basename( $file['name']) . " has been uploaded to " . $target_path . "</br></br>";

                    } else {
                        $uploadResponse .= "There was an error uploading the file, please try again! </br>";
                        $uploadResponse .= "File size: " . ($file["size"] / 1024) . "kb</br>";
                        $uploadResponse .= "Max size: " . ($maxsize / 1024) . "kb";
                    }

                $status = "success";
                $Return["link"] = $imageLink;

                /* ---------------------------------- */
                /* - Time to upload that image, yo. - */
                /* ---------------------------------- */

                $imageSql = "INSERT INTO images (id, link, model_id, addedon) VALUES (".
                    "null, " .
                    PrepSQL($imageLink) . ", " .
                    PrepSQL($myId) . ", " .
                    PrepSQL($date) . ")";

                mysql_query($imageSql) or die("Images: " . mysql_error());


            } else {
                $uploadResponse = "The file must less then " . ($maxsize / 1024) . "kb.";
                $status = "failure";
                $Return["error"] = $uploadResponse;
            }

        } else {
                $uploadResponse = "The file must be a .jpg file.";
                $status = "failure";
                $Return["error"] = $uploadResponse;
        }
    } else {
            $uploadResponse = "No Image.";
            $status = "failure";
            $Return["error"] = $uploadResponse;
    }


/* ------------------------- */
/* -  Lets Send it back :) - */
/* ------------------------- */

    $Return["status"] = $status;
    $Return["id"] = mysql_insert_id();
    $Return["traveler"] = $file;

    str_replace('\\/', '/', json_encode($Return));
    echo json_encode($Return);
?>

RAW Response:

<script>
    function hairEyesFind(haireyes){
        if (haireyes == "blonde") {
            return "z";
        };
        if (haireyes == "dirty blonde") {
            return "b";
        };
        if (haireyes == "auburn") {
            return "c";
        };
        if (haireyes == "brown") {
            return "d";
        };
        if (haireyes == "black") {
            return "e";
        };
        if (haireyes == "red") {
            return "f";
        };
        if (haireyes == "blue2") {
            return "g";
        };
        if (haireyes == "green2") {
            return "h";
        };
        if (haireyes == "hazel2") {
            return "i";
        };
        if (haireyes == "brown2") {
            return "j";
        };
    }
</script>{"type":"image\/jpeg","link":"http:\/\/scoutsamerica.com\/uploads\/485604_10201093620571706_1239548317_n_5119195.jpg","status":"success","id":281,"traveler":{"name":"485604_10201093620571706_1239548317_n.jpg","type":"image\/jpeg","tmp_name":"\/tmp\/phpX1qywo","error":0,"size":60368}}
1
  • I would drop a print_r($Return) before sending the JSON back to make sure the data being sent back is what you think is being sent back. Commented May 13, 2013 at 17:38

2 Answers 2

6

unexpected token probably means you've got a corrupted JSON response from the server. Most likely it's an html-formatted PHP error/warning, embedded before/after the json data, e.g.

<p>PHP Warning: blah blahblah</p>[...json text here ...]

Since html is not valid json, you get that error message. So check out the RAW response from the server for that particular ajax call, and see what's coming back from the server.

Sign up to request clarification or add additional context in comments.

6 Comments

Forgive me, that's one thing I haven't had the pleasure of doing yet. How does one go upon checking the RAW response from a server?
it can be as simple as: success: function(data) { console.log(data); }.
its returning one of my javascript functions before the json.... !? I pasted it above.
Any idea why? Javascript syntax error? It couldnt be in the PHP could it?
it's a JS error at the JSON.parse() line, because whatever's PHP sending over is not valid json. so see what php's sending, then fix the error in the php code.
|
0

A few things:

  1. Why are you using \/ instead of just /?
  2. Shouldn't the first return statement in the response be "a" not "z"?
  3. Why do you have a block of JSON at the end of the response?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.