Skip to content
Advertisement

Laravel Ajax Call to a function in controller

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 :

$.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

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

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

$.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

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

Route::post('/orderdata/{postdata}', 'DashBoardController@OrderData')
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement