How to do ajax in Laravel 5.2
- Create a dummy button on your view: 1
2<input type = "submit" class = "btn btn-primary m-d do-ajax" value = "AJAX" />
{{ csrf_field() }} {{-- This will include a unique token which will we will pass along with our AJAX post --}} - On your JS script, add the following: 1
2
3
4
5
6
7
8
9
10
11
12
13
14$('body').on('click', '.do-ajax', function () {
$.ajax({
url: './page/do-ajax',
headers: {'X-CSRF-TOKEN': $('input[name=_token]').val()},
data: {
test: 'test'
},
type: 'POST',
datatype: 'JSON',
success: function (resp) {
alert(resp);
}
});
}); - On your controller add this new method: 1
2
3
4
5
6
7public function do_ajax(Request $request) {
if( $request->ajax() ) {
return response()->json([
'testdata' => 'it works!'
]);
}
} - On your route, add the following code: 1Route::post('/page/do-ajax', 'PageController@do_ajax');
- Try it out, click the button. You should get the response of the ajax request: “it works!”.
Do you need help with a project? or have a new project in mind that you need help with?
Contact Me