Kaherdin Kaherdin - 4 months ago 10
Ajax Question

Return a variable result of a function to an Ajax response

This is my Ajax call :

$("#cover-input").change(function(){
var file_data = $("#cover-input").prop("files")[0];
var form_data = new FormData();
form_data.append("cover_file", file_data);
//kaherdin
$.ajax({
url: 'update-cover',
type: 'POST',
dataType: 'script',
data: form_data,
contentType: false,
processData: false,
async: false,
success: function(resp){
console.log(resp);
},
error: function(err){
console.log('Likes error', err);
}
});
readURL_cover(this);
});


I've a function that basicly trim and upload a file on change.

public function updateCover(Request $request) {
$user = Sentinel::check();
$destinationPath = public_path('uploads/users');

if ($fileCover = $request->file('cover_file')) {
$input_cover = time().'.'.$fileCover->getClientOriginalExtension();
$img = Image::make($fileCover->getRealPath());
$img->fit(1920, 555, function ($constraint) {
$constraint->aspectRatio();
})->save($destinationPath.'/'.$input_cover);
// $user->cover = $input_cover;

$response = $input_cover;
return $response;
}


But this get me an error. I just want to get "input_cover" back to my ajax call so I can show the updated picture.
If I change : $response = $input_cover to $response = [$input_cover]; it kinkds of work but the input is like : ["my_pic.jpg"] so it's not nice.

btl btl
Answer Source

You should return a JsonResponse like so:

return response()->json(['input_cover' => $input_cover]);

Check this for responses in json and how they work https://laravel.com/docs/5.4/responses#json-responses