I am new to laravel and I want to make an ajax call to a function written in controller. I have done the following but not working.
In View :
JavaScript
x
$.ajax({
type: "POST",
url: 'OrderData', // Not sure what to add as URL here
data: { id: 7 }
}).done(function( msg ) {
alert( msg );
});
My Controller which is located inside app/controllers/DashBoardController.php and inside DashBoardController.php I have
JavaScript
class DashBoardController extends BaseController {
public function DashView(){
return View::make('dashboard');
}
public function OrderData(){ // This is the function which I want to call from ajax
return "I am in";
}
}
My Question is how can I make an ajax call from view on page load to a function inside my DashBoardController.php ?? Thanks.
Advertisement
Answer
In your routes.php
file add
JavaScript
Route::post('/orderdata', 'DashBoardController@OrderData');
Then use your ajax call to send data to /orderdata
the data will be passed through to your OrderData
method in the DashBoardController
So your ajax call would become
JavaScript
$.ajax({
type: "POST",
url: '/orderdata', // This is what I have updated
data: { id: 7 }
}).done(function( msg ) {
alert( msg );
});
If you want to access the data you will need to add that into your method like so
JavaScript
class DashBoardController extends BaseController {
public function DashView(){
return View::make('dashboard');
}
public function OrderData($postData){ // This is the function which I want to call from ajax
//do something awesome with that post data
return "I am in";
}
}
And update your route to
JavaScript
Route::post('/orderdata/{postdata}', 'DashBoardController@OrderData')