Ayan Ayan - 5 months ago 21
Javascript Question

Ajax success function not outputting text sent by Php script

I am uploading multiple files with this PHP script below:

<?php

if(isset($_FILES['uploadfile'])){
$total_files = count($_FILES['uploadfile']['name']);
if( $total_files > 0){

for($i=0; $i<$total_files; $i++) {

$file_name = $_FILES['uploadfile']['name'][$i];
$file_size = $_FILES['uploadfile']['size'][$i];
$file_tmp = $_FILES['uploadfile']['tmp_name'][$i];
$file_type = $_FILES['uploadfile']['type'][$i];

$upload_Path = "storage/".$file_name;

//var_dump($file_size);
//die;

if($file_size > 8000000){
echo ('Total upload size must be less than 8 MB.');
die;
}

if($file_tmp == ""){
echo ('There is no file path.');
die;
}
else{
if(!file_exists($upload_Path)){
move_uploaded_file($file_tmp, $upload_Path);
}
else{
$name = pathinfo($file_name, PATHINFO_FILENAME);
$ext = pathinfo($file_name, PATHINFO_EXTENSION);
$new_name = $name.rand().'.'.$ext;

$new_Path = "storage/".$new_name;
move_uploaded_file($file_tmp, $new_Path);
}
}
}
}
die('File uploaded successfully!');
}
?>


but the problem is that whenever an error occurs such as
echo ('Total upload size must be less than 8 MB.');
it doesn't get outputed using ajax. But when a successful upload is done it shows
File uploaded successfully!
.

My AJAX is as follows:

$.ajax({
type:'POST',
url: 'mupld.php',
data: formdata,
processData:false,
contentType:false,
success: function(response){
alert('Success: '+response);
},
error: function(xhr, status, error){
alert('Error: '+status+' '+error);
}
});


On doing a var dump I dont get any output for uploads above 8mb but for below that I get

Success: <pre class='xdebug-var-dump' dir='ltr'><small>int</small> <font color='#4e9a06'>3283515</font>
</pre>

Answer

@Jeff Bucket was right, so I edited my answer:

Actually, you should handle those errors in your success callback. The error() callback is reserved for situations where the connection between browser and server just breaks, and the error() parameters expect to handle those kind of situations, for example a typical textStatus error should be 'Not Found' or 'Internal Server Error', but no 'Total upload size must be less than 8 MB.'.

You should return an array with information you can use in the client, and handle that in success(), like:

try{

if(isset($_FILES['uploadfile'])){
    $total_files = count($_FILES['uploadfile']['name']);
    if( $total_files > 0){

        for($i=0; $i<$total_files; $i++) {

            $file_name = $_FILES['uploadfile']['name'][$i];
            $file_size = $_FILES['uploadfile']['size'][$i];
            $file_tmp  = $_FILES['uploadfile']['tmp_name'][$i];
            $file_type = $_FILES['uploadfile']['type'][$i];

            $upload_Path = "storage/".$file_name;

            //var_dump($file_size);
            //die;

            if($file_size > 8000000){
                echo json_encode( array('status' => 'failure'  , 'msg' => 'Total upload size must be less than 8 MB.')  );
                die();
            }

            if($file_tmp == ""){
                echo json_encode( array('status' => 'failure'  , 'msg' => 'There is no filepath.')  );
                die;
            }
            else{
                if(!file_exists($upload_Path)){
                    move_uploaded_file($file_tmp, $upload_Path);
                }
                else{
                    $name = pathinfo($file_name, PATHINFO_FILENAME);
                    $ext  = pathinfo($file_name, PATHINFO_EXTENSION);
                    $new_name = $name.rand().'.'.$ext;

                    $new_Path = "storage/".$new_name;
                    move_uploaded_file($file_tmp, $new_Path);
                }
            }
        }
    }
    echo json_encode( array('status' => 'success'  , 'msg' => 'File uploaded succesfully.')  );
    die();
}

else{

    echo json_encode(array("status" => "error" , "msg" => "No file was found when processing uploaded files" ) );
    die();
}


}
catch(Exception $ex){

echo json_encode(array('status' => 'error' , 'msg' => 'An unhandled exception raised: ' . $ex->getMessage() ) );
die();
}
finally{
    die();
}

Then in your $.ajax() function:

$("#uploadfile").change(function(){ 
//submit the form here 
var files = $("#fileupload")[0]; 
var formdata = new FormData(files); 
$.ajax({ 
    type:'POST', 
    url: 'mupld.php', 
    data: formdata, 
    processData:false, 
    contentType:false, 
    success: function(response){ 

             response = JSON.parse(response);
             alert(response.msg);

        }, 
    error: function(xhr, textStatus, error){ 
        console.log('Error: '+textStatus+' '+error); 
    } 
}); 

If you specifically want to handle this in the error() callback, you should set the response code of the php script to 500 -or whatever custom code- using header().

Comments