Laravel 5 AJAX Sort order data (jQuery Sortable) without HTML form

I'm trying to keep the sort order for each article in the help center for my new site using Laravel 5, and with a few problems getting it to work. I use jQuery UI .sortable to place elements on the page, and since there will be several sections on the site where the areas will be sorted, my jQuery script is built in such a way that it has one script for all purposes. Therefore, the use of data-* attributes and route references.

Here is the code that I still have:

routes.php

 Route::post('admin/help-centre/category/{category_id}/section/{section_id}/article/sort-order', ' AdminHelpCentreArticleController@sortOrder '); 

AdminHelpCentreArticleController.php

 public function sortOrder($category_id, $section_id) { /* Return ------------------------------------- */ return [ 'category_id' => $category_id, 'section_id' => $section_id ]; } 

show.blade.php (list of articles for guidance)

 <ul id="help-center-articles-sort" class="sortable"> @foreach ($helpCentreArticles as $helpCentreArticle) <li class="sortable-element" data-sortable-element-id="{{ $helpCentreArticle->id }}"> <a href="{{ action(' AdminHelpCentreArticleController@show ', array($helpCentreCategory->id, $helpCentreSection->id, $helpCentreArticle->id)) }}" target="_self">{{ $helpCentreArticle->title }}</a> </li> @endforeach </ul> <a href="{{ $helpCentreSection->id }}/article/sort-order" target="_self" class="button bm-remove w-full sortable-save" data-sortable-id="help-center-articles-sort">Save Order</a> 

scripts.js (includes CSRF token _token )

 var csrfToken = $('meta[name="csrf-token"]').attr('content'); $.ajaxPrefilter(function(options, originalOptions, jqXHR) { if (options.type.toLowerCase() === 'post') { options.data += options.data?'&':''; // add leading ampersand if `data` is non-empty options.data += '_token=' + csrfToken; // add _token entry } }); $(document).ready(function() { $('.sortable').sortable(); $('.sortable-save').on('click', function(e) { e.preventDefault(); var route = $(this).attr('href'), sortableID = $(this).attr('data-sortable-id'); var data = $('#' + sortableID + ' .sortable-element').map(function() { return $(this).attr('data-sortable-element-id'); }).get(); $.ajax({ type: 'POST', url: route, dataType: 'json', data: { id_array: data }, success: function(data) { console.log(data); }, error: function(data) { console.log(data); }, }); }); }); 

Everything still works in terms of a response in the console, which is Object {category_id: "1", section_id: "1"} . But no matter what I try, I can not pass the data card to the controller to use it.

I tried a bunch of guesses, since I cannot find any decent AJAX tutorial in Laravel 5 anywhere, and I tried things like adding the $data parameter to the sortOrder() method, I tried Input::all() and Request::all , but all this returns errors (I assume this is not the actual form?).

Once I get the data that will be passed to the controller, I can easily save the sort order in the database. But I can’t get to this stage, any ideas?

EDIT

I should probably point out that I have a HelpCentreArticle model and a HelpCentreArticleRequest request, here are some of the code from each file, if they are also needed:

HelpCentreArticle.php

 class HelpCentreArticle extends Model { protected $fillable = [ 'category_id', 'section_id', 'title', 'content', 'excerpt', 'is_visible', 'sort_order', 'created_by', 'updated_by', ]; } 

HelpCentreArticleRequest.php

 class HelpCentreArticleRequest extends Request { /* Authorization ------------------------------ */ public function authorize() { return true; } /* Validation rules --------------------------- */ public function rules() { $rules = [ 'title' => 'required|min:3', 'content' => 'required|min:10', ]; return $rules; } } 

I was not sure that I needed to add HelpCentreSectionRequest $request as the last parameter of the sortOrder() method, so I could use $request->all() , but it just returns 422 (Unprocessable Entity) to the console log.

+6
source share
2 answers

So it seems that the right way was to use Input::get('id_array'); instead of $_POST['id_array']; I tried, but when I initially tried this, I did not include use Input; at the top of my controller, as I thought it was already available, but it wasn’t.

Adding use Input; and using Input::get(); now works as expected.

Here is the updated code:

AdminHelpCentreArticleController.php

 public function sortOrder($category_id, $section_id) { /* Query Select ------------------------------- */ $helpCentreCategory = HelpCentreCategory::findOrFail($category_id); $helpCentreSection = HelpCentreSection::findOrFail($section_id); /* Variables ---------------------------------- */ $id_array = Input::get('id_array'); $sort_order = 1; /* Query Update ------------------------------- */ foreach($id_array as $id) { $helpCentreArticle = HelpCentreArticle::where('id', $id)->first(); $helpCentreArticle->sort_order = $sort_order; $helpCentreArticle->save(); $sort_order++; } /* Return ------------------------------------- */ return ['success' => true]; } 

Then you can explicitly access success for the if else in your jQuery to manipulate the page.

+4
source

My UI implementation is sorted using Laravel

index.blade.php

 ... @foreach($photos as $photo) <tr data-sortable="{{ $photo->pivot->position }}" data-id="{{ $restaurant->id }}" data-photo-id="{{ $photo->pivot->photo_id }}"> <td> <i class="fa fa-sort" aria-hidden="true"></i> </td> ... </tr> @endforeach <script type="text/javascript"> $("#sortable-ui tbody").sortable({ helper: fixHelper, update: function(event, ui) { $("#sortable-ui tbody tr").each(function(index){ console.log($(this).data('id')+', '+(index+1)); $.ajax({ url: '{{ route('owner.photo.update.position') }}', type: 'POST', data: 'restaurant_id='+$(this).data('id')+'&photo_id='+$(this).data('photo-id')+'&position='+(index+1) }) .done(function (response) { console.log(response); }) .fail(function (jqXhr) { console.log(jqXhr); }); }); } }).disableSelection(); </script> 

scripts.js

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

AjaxController.php

 public function updatePhotoPosition(Request $request) { $restaurant = $this->restaurantRepository->getById($request->get('restaurant_id')); $photoId = $request->get('photo_id'); $photo = $restaurant ->photos() ->wherePivot('photo_id', $photoId) ->first(); $photo->pivot->position = $request->get('position'); $photo->pivot->save(); } 
0
source

Source: https://habr.com/ru/post/983835/


All Articles