Latest

Thursday, July 6, 2017

Getting AJAX data in Laravel

Asked by: Chuck Le Butt


I'm pulling my hair out here. I cannot access data submitted through an Ajax request in Laravel. I've tried using formData and just plain objects. Every time I just see a default Request object in Laravel and not the data I've submitted.

Here's my JS (TypeScript):

$('#save-section-order').on('click', function(e){
   e.preventDefault();

   let $this = $(this);
   let data = [];

   const order = $('#sortable').sortable('serialize');
   const project_id = $this.data('id');
   const url = "/admin/save-new-order";
   const csrfToken = $this.data('csrf');

   $.ajax({
       url: url,
       type: 'POST',
       data: {
           order: order,
           project_id: project_id
       },
       contentType: false,
       processData: false,
       headers: {
           'X-CSRF-TOKEN': csrfToken,
           'X-HTTP-Method-Override': 'PATCH'
       },
       success: function( msg ) {
           if ( msg.status === 'success' ) {
               $this.parent().parent().fadeOut();
           }
       },
       error: function( data ) {
           if ( data.status !== 200 ) {
               $this.parent().parent().css('background-color', '#f2dede');
           }
       }
   });
});

Here's my web route:

Route::patch('/admin/save-new-order', 'Admin\ProjectsController@saveSectionsOrder');

Here's my ProjectsController:

public function saveSectionsOrder(Request $request) {

    dd($request);

}

The output is always a generic Request object and I cannot retrieve the data I submitted through $request->order or $request->input('order').

I know I'm missing something really obvious, but I just can't see what.



Source

No comments:

Post a Comment

Adbox