Petr Bečka Petr Bečka - 7 months ago 10
Javascript Question

ajax request call ending with error

I'm having a problem with ajax call. I want to pass information on the server side but always when I call ajax request it ends with error. Weird is, that I used exactly the same code, same lines, in previous project.

This is my ajax request (php_session_id is not undefined, I'm checking that every time):

$.ajax({
data: { unique: php_session_id },
url: 'server/uploading_files.php',
method: 'POST',
success: function (response) {
console.log("response");

},
error: function() {
console.log("some error");
}
});


And this is my uploading_files.php file:

header('Content-Type: application/json');
session_start();

if( isset( $_POST['unique'] ) ) {$_SESSION['unique_id'] = $_POST['unique'];}

$path_to_save = 'upload/' . $_SESSION['unique_id'] . '/';
if( !is_dir( $path_to_save ) ) {
if ( !mkdir( $path_to_save, 0777, true ) ) {
die('Failed to create folder for uploaded photos...');
}
}


Error codes when I use

error: function(jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
}


are:


jqXHR - Object {readyState: 4, responseText: "Failed to create folder
for uploaded photos...", status: 200, statusText: "OK"}

textStatus - parsererror

errorThrown - SyntaxError: Unexpected token F(…)


Don't you have any idea how to solve it, please?

Answer

If you are just looking to get it working, I recommend Ravishanker Kusuma's Hayageek jQuery File Upload plugin. I don't usually recommend plugins, but this one is excellent. It does almost all the work for you. Why re-invent the wheel?

http://hayageek.com/docs/jquery-upload-file.php

He breaks down the process into four simple steps, that basically look like this:

Look for //1 //2 //3:

<head>
  // (1) Load the js files (note that it requires jQuery, which we also load)
    <link href="http://hayageek.github.io/jQuery-Upload-File/uploadfile.min.css" rel="stylesheet">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script src="http://hayageek.github.io/jQuery-Upload-File/jquery.uploadfile.min.js"></script>   // (1)
</head>
<body>
    <div id="fileuploader">Upload</div>  // (2) Create DIV
    <script>
        $(document).ready(function(){
            $("#fileuploader").uploadFile({  // (3) initialize plugin
                url:"my_php_processor.php",
                fileName:"myfile"
            });
        });
    </script>
</body>

The final (fourth) step is to create a PHP file with same name as specified above in the jQuery code (in this case my_php_processor.php) to receive and process the file:

my_php_processor.php:

<?php
    $output_dir = "uploads/";
    $theFile = $_FILES["myfile"]["name"];
    move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir.$fileName);

Note the relationship between myfile in the PHP ($_FILES["myfile"]), and the filename myfile specified in the jQuery code block.

On the Hayageek web page, study the upload.php example on the Server tab.

Note that you can also pass additional variables to the my_php_processor.php processor file by using dynamicFormData. See this other example:

$("#fileuploader").uploadFile({
    url:"my_php_processor.php",
    fileName:"myfile",
    dynamicFormData: function(){
        return {
            //my_php_processor.php will receive POST vars below
            newSubj: $("#newSubj").val(),
            newBody: $("#newBody").val(),
        };
    },
    onSuccess:function(files,data,xhr,pd){
        //files: list of files
        //data: response from server
        //xhr : jquer xhr object
        alert(xhr.responseText); //displays data ECHOd by `my_php_processor.php`
    }
});

my_php_processor.php:

<?php
    $n = $_POST['newSubj'];
    $b = $_POST['newBody'];
    $uploadedFile = $_FILES["myfile"]["name"];
    //etc.
    echo 'This will display in the alert box';

jsFiddle Sample Code - Click on Image Example

Comments