Sharon Haim Pour Sharon Haim Pour - 4 months ago 26
Ajax Question

Laravel 5: Fetch ajax data in route and pass to controller

I'm using Laravel 5 and want to make ajax call to a controller with some data:

$.ajax({
url : "/getOrgById",
data : JSON.stringify({id:1})
})


The
routes.php
has:

Route::get('/getOrgById', 'HomeController@getOrgById');


HomeController.php
:

public function getOrgById($data) {
//code here fails with message 'Missing argument 1 for HomeController::getOrgById()
}


How can I pass the data from ajax to route and then to controller?

Answer

I think the below example is what you're looking for

Route

Route::post('/getOrgById', 'HomeController@getOrgById');

Controller

public function getOrgById(Request $request) {
    $id = $request->input('id');
}

JS

var myJsonData = {id: 1}
$.post('/getOrgById', myJsonData, function(response) {
    //handle response
})
Comments