Reputation: 48818
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.
Upvotes: 1
Views: 476
Reputation: 9596
You have contentType: false
, which tells $.ajax that you have no content.
When sending data to the server, use this content type. Default is "application/x-www-form-urlencoded; charset=UTF-8", which is fine for most cases. If you explicitly pass in a content-type to $.ajax(), then it is always sent to the server (even if no data is sent). As of jQuery 1.6 you can pass false to tell jQuery to not set any content type header. Note: The W3C XMLHttpRequest specification dictates that the charset is always UTF-8; specifying another charset will not force the browser to change the encoding. Note: For cross-domain requests, setting the content type to anything other than application/x-www-form-urlencoded, multipart/form-data, or text/plain will trigger the browser to send a preflight OPTIONS request to the server.
Change that to something more appropriate, or remove it to allow it to default to application/x-www-form-urlencoded
.
Also, you may want to keep processData: false
, depending on the nature of the data you're sending, but otherwise remove that, too.
Upvotes: 3
Reputation: 541
For receiving data from request object you must use
$request->all()
This command will get you array of passed data. Or you can access directly by name:
$request->input('order')
Upvotes: 0