Kaherdin Kaherdin - 9 months ago 25
Ajax Question

Return a variable result of a function to an Ajax response

This is my Ajax call :

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

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) {
// $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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download