SiNi_Si's avatar

getting data back to javascript from laravel controller

I having a hard time getting a response from my laravel controller sent by ajax. I have removed all the auth middleware and hard coded the exact response I need to get back. Still nothing.

Here is the ajax from my old site plain php and worked fine. This would call a php file and would echo back the path and file to insert in summernote.


function sendFile(file, el) {
    var form_data = new FormData();
    form_data.append('file', file);
    $.ajaxSetup({
        headers: {
            'X-CSRF-Token': $('meta[name=_token]').attr('content')
        }
    });
    $.ajax({
        data: form_data,
        type: "POST",
        url:"{{ url('/Upload') }}",
        cache: false,
        contentType: false,
        processData: false,
        success: function(url) {
            $(el).summernote('editor.insertImage', url);
        }
    });
}

here is the post route.


Route::post('/Upload', 'UploadController@support');

Here is the hard coded response to send back to ajax


public function support(Request $request){
      return '/public/images/test/IMG_1579.jpg';
    }

The ajax sends a file and the controller would upload the file and return its new file name and path in one string to be added to summernote.

Any thoughts would be great Thanks

0 likes
9 replies
tykus's avatar

What are you getting instead of the expected string?

RamjithAp's avatar

Try

public function support(Request $request){
      return response()->json(['url'=> '/public/images/test/IMG_1579.jpg']);
    }

And

   success: function(data) {
            $(el).summernote('editor.insertImage', data.url);
        }
SiNi_Si's avatar

Thanks tykus - nothing gets added to summernote. How can I echo a response to see what i'm getting back?

Thanks RamjithAp - No change on this. I have even added dataType:'JSON',

SiNi_Si's avatar

I have added...


error: function(data) {
        alert(data.url);
 }

I just get back "undefined"

RamjithAp's avatar

Open your browser developer tools -> network section and check when you to do the upload what request goes and what response comes.

SiNi_Si's avatar

244:890 Uncaught ReferenceError: url is not defined at Object.error (244:890) at i (jquery.min.js:2) at Object.fireWith [as rejectWith] (jquery.min.js:2) at z (jquery.min.js:4) at XMLHttpRequest. (jquery.min.js:4)

RamjithAp's avatar
Level 10

Try changing your token name as below. Use this in the head section:

<meta name="csrf-token" content="{{ csrf_token() }}">

and get the csrf token in ajax:

$.ajaxSetup({
  headers: {
    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
  }
});

Please refer Laravel Documentation https://laravel.com/docs/5.6/csrf#csrf-x-csrf-token

SiNi_Si's avatar

That was it! The CSRF token has fixed this.

Thanks

Please or to participate in this conversation.