jeudi 29 septembre 2016

Laravel 5.x Ajax Post from an array not working

I have been looking everywhere for solutions and I am convinced I am doing everything right.

I have a list of IDs in an array that I need to channel through to the controller for deletion but the request object always gives me an empty array when I do $request->all() but if I dump the request object itself I am able to see it and its related properties and methods.

JavaScript

var data = [id: 14, id:77, id:138]; //We will convert this to a json string

$.ajax({
  type   : 'POST',
  url    : '/orders/cancel',
  data   : JSON.stringify(data), //Outputs [{"id":"x"},{"id":"x"}]
  headers: { 'X-CSRF-TOKEN':token },
  success: function(){ //the usual },
  error: function(){ //the usual }
});

Laravel Route

Route::any('/orders/cancel', 'BackOrderedOrdersController@cancelAction');

The Controller

namespace My\Namespace;

use Illuminate\Http\Request;
//other irrelavant `use` statements omitted
class BackOrderedOrdersController extends Controller
{
   public function cancelAction(Request $request)
   {
      dd($request->all()); //This just outputs '[]' : empty array
   }
 }

The response status is 200 meaning everything is fine but the posted data does not reach the controller for some reason.

This is also a first time I had to work with Ajax Post without my data coming from a form and also I am a bit reluctant in terms of whether that is the issue.

My bet is around this content type defined as application/x-www-form-urlencoded;charset=UTF-8 by FIREBUG output even when I specified data type as json. I am partially aware of what this content-type and encoding is all about entails but in this instance.

Can someone pinpoint me to the right direction as to where the data gets missed? Is it a JQuery issue, Laravel issue or what?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2doLq04
via IFTTT

Aucun commentaire:

Enregistrer un commentaire