mardi 28 février 2017

formData passed through ajax is not being available in Laravel

here is my form:

<form role="form" action="" method="post" enctype="multipart/form-data">
        Select an excel file to upload:
        <input type="file" name="fileToUpload" id="fileToUpload" multiple>
        <input type="submit" value="upload" name="submit">
        
</form>

the js code :

$('#fileToUpload').on('change',function(e){

                 var myFile = e.target.files[0];
                 var f_data = new FormData(); 
                 f_data.append('file', myFile);

                 $.ajax({
                    type : 'get',
                    data : f_data,
                    dataType : 'JSON',
                    url : "",
                    processData: false,
                    contentType: false,

                 }).done(function(data){
                    console.log(data);
                 });
});

here is the route ajax call is being made to:

Route::get('/ex2','ExcelController@ajax')->name('excel.form.ajax');

my code in the Laravel ExcelController file :

public function ajax(Request $r)
{
    return ['all_data' => $r->all(), 
            'request_files' => $r->allFiles(), 
            '$_FILES' => $_FILES, 
            'valid' => $r->file('file')->isValid()
           ];
}

............. now from the controller method, when i return the array with the "valid" key, the output is an object with bunch of empty arrays. but i do get a return at least.

but when i add the

'valid' => $r->file('file')->isValid()

in the array to be returned, as shown in the code above,the return is an internal server error, this :

GET http://localhost/larajects/ghureBerai02/public/ex2?[object%20FormData] 500 (Internal Server Error)

which i think is happening because isValid() method is being called on empty. which means the formData was not passed for some reason.

even the

if($r->all()) 

returns false

can anybody please tell me what could the reason be for this problem?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire