- 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!”.
Category
Category: Laravel
How to do ajax in Laravel 5.2
Adding Helper Files in Laravel 5
- Create a folder in your “app” directory, name it “Helpers.
- Then within your Helpers folder, add your function files.
Name your files anything you like.
Having a folder with multiple files allows us to avoid one big file that gets
too long and unmanageable. - Open your command line then navigate to your project ROOT folder
then create a service provider called “HelperServiceProvider.php” by
running the php artisan command:1php artisan make:provider HelperServiceProvider - Open the file: app/providers/HelperServiceProvider.php
Update the “register” method with the following snippet:1
2
3
4
5
6public function register()
{
foreach (glob(app_path().'/Helpers/*.php') as $filename){
require_once($filename);
}
} - Lastly, register the service provider in your config/app.php in the providers array
1
2
3'providers' => [
'App\Providers\HelperServiceProvider',
]Now any file in your Helpers directory is loaded, and ready for use.
Moving Laravel 5.6 from local machine to live server
- Zip your laravel app files.
Laravel default installation has over 6000 files, it’s recommended that you zip your files
then unzip it in your Cpanel Web Explorer. - Export your app’s database then set it up on your server.
- After you have uploaded your laravel app files, open the .env file found on the root
directory of your laravel app.
Update the database credentials and the APP_URL. - Open your .htaccess file, then add the following line just bellow RewriteEngine On:
1RewriteBase /
- That’s it!, now check your live site.
- If you are getting 403 Forbidden Access or 500 Internal Server message, try changing
the permissions of your storage folder found on the root directory of your laravel app.
Set the permission to 0777. - If you are still having issues, contact your hosting.