In this tutorial we are going to see how to perform laravel ajax example of get and post request. Most of the new beginners will have trouble for the first time while going through it.
In this tutorial we will perform both laravel ajax GET request and POST request separately. Before moving to the tutorial lets know what is ajax first.
So, What is Ajax ?
- AJAX stands for Asynchronous Javascript and XML which helps you to dynamically load or change the content of the page without having to reload the entire page. This includes the following 3 things :-
- Sending data to the server from the background.
- Retrieving the data from the server after the page have been loaded ( These examples can be found on most of the ecommerce websites.)
- Also updating the page without having to reload the page.
While fetching the data from the server in the background we generally display them in an html element so DOM ( Document Object Model ) in manipulated while fetching data from server.
By now you should have understand that little bit of knowledge of javascript is required to do this. But no worries we, we will provide step by step so that you can learn the javascript on the way.
Lets get Started :-
We are going to perform ajax get request first and then later post request so that you can see what are the differences.
What we are going to do ?
- First we will insert something into the database.
- We will retrieve the same data that we have just inserted in first step.
I assume that you have a dummy database with tables are ready. Take a look at my migration example below :-
1 2 3 4 5 6 7 8 9 |
public function up() { Schema::create('tbl_posts', function (Blueprint $table) { $table->increments('id'); $table->string('title'); $table->text('description'); $table->timestamps(); }); } |
Create a file in your resources/views
folder called insert.blade.php
Setup your view page. I am using bootstrap in order to give elegant styles to forms and buttons.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
<!DOCTYPE html> <html lang=""> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Laravel Ajax</title> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous"> </head> <body> <div class="container"> <div class="row" style="margin-top: 30px;"> <div class="col-md-offset-2 col-md-6"> <!-- Div with an id to display success message or failed message --> <div id="success"> </div> <form action="{{ url('insert-ajax') }}" method="GET" onsubmit="return InsertViaAjax();" id="ajax-form-submit"> <div class="form-group"> <label for="">Title</label> <input type="text" name="title" id="title" placeholder="Enter Post title" class="form-control"> </div> <div class="form-group"> <label for="">Textarea</label> <textarea name="description" id="description" cols="30" rows="10" placeholder="Enter Description" class="form-control"></textarea> </div> <div class="form-group"> <button class="btn btn-primary">Insert</button> </div> </form> </div> </div> </div> <script src="https://code.jquery.com/jquery.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script> </body> </html> |
Now the ajax javascript code,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
function InsertViaAjax() { var form = $("#ajax-form-submit"); // Give the loading icon when data is being submitted $("#success").val('loading...'); var title = $("#title").val(); var desc = $("#description").val(); //Run Ajax $.ajax({ type:"GET", url:"{{url('insert-ajax')}}/"+title+"/"+desc, success: function(data) { $("#success").html('Inserted into database').delay(3000).fadeOut(); } }); // To Stop the loading of page after a button is clicked return false; } |
Now setting up the routes on resources/web.php
1 2 3 4 5 |
Route::get('insert-ajax/{title}/{desc}', function(Request $request, $title, $description) { DB::table('tbl_posts')->insert(['title'=>$title,'description'=>$description]); }); |
Laravel Ajax Post Request
If you have noticed that using GET request in ajax will lead to problems :-
- Everyone will know what data you are passing through the URL. Developers and hackers can easily see the data.
- You have to add each extra parameter with the increase in form fields. You can pass it in array but its not feasible to do it. So will prefer the POST method.
Laravel Ajax Post Request
Lets make it quick by changing the same form we used earlier. Change the method in the form from GET to POST.
If you have noticed that when using post request while submitting the form csrf token need to be applied so we also have to place csrf token in the form. Go ahead and place it {!! csrf_field() !!}
Next, we need to place csrf token in top of our insert.php view file. Paste this code just below closing of title tag.
1 |
<meta name="_token" content="{{csrf_token()}}" /> |
Little change in the code of Ajax to perform POST REQUEST.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
function InsertViaAjax() { var form = $("#ajax-form-submit"); // Give the loading icon when data is being submitted $("#success").val('loading...'); var form_data = $("#ajax-form-submit").serialize(); $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content') } }); $.ajax({ type:"POST", url:"{{url('insert-ajax')}}", data : form_data, success: function(data) { $("#success").html('Inserted into database').delay(3000).fadeOut(); } }); // To Stop the loading of page after a button is clicked return false; } |
This is all, if you want to insert data via ajax. If you want to display the inserted data just below without reloading the page then, you have to make just a little change in your database query and return json response.
lets do it,
Create new <ul>
with an id called inserted_data
.
Change your web.php
as below :-
1 2 3 4 5 6 7 8 9 10 11 12 13 |
// Post Request (While going through form data we dont need to pass data through url) Route::post('insert-ajax', function() { $data = Input::except('_token'); DB::table('tbl_posts')->insert($data); //Fetch the last record inserted $id=DB::getPdo()->lastInsertId(); $inserted_data = DB::table('tbl_posts')->where('id',$id)->first(); return Response::json(['success'=>$inserted_data]); }); |
Change in Ajax Code :-
Add this after the success function.
1 |
$("#inserted_data").append('<li>'+data.success.title+'</li>'); |
Are you confused ? Why not have look the full code just below step wise step :-
First your routes/web.php
:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
Route::get('/', function() { // load the select page return view('insert'); }); // Post Request (While going through form data we dont need to pass data through url) Route::post('insert-ajax', function() { $data = Input::except('_token'); DB::table('tbl_posts')->insert($data); //Fetch the last record inserted $id=DB::getPdo()->lastInsertId(); $inserted_data = DB::table('tbl_posts')->where('id',$id)->first(); return Response::json(['success'=>$inserted_data]); }); |
Now your view file with complete javascript code :-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 |
<!DOCTYPE html> <html lang=""> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="_token" content="{{csrf_token()}}"> <title>Laravel Ajax</title> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous"> </head> <body> <div class="container"> <div class="row" style="margin-top: 30px;"> <div class="col-md-offset-2 col-md-6"> <!-- Div with an id to display success message or failed message --> <div id="success"> </div> <form action="{{ url('insert-ajax') }}" method="POST" onsubmit="return InsertViaAjax();" id="ajax-form-submit"> {!! csrf_field() !!} <div class="form-group"> <label for="">Title</label> <input type="text" name="title" id="title" placeholder="Enter Post title" class="form-control"> </div> <div class="form-group"> <label for="">Textarea</label> <textarea name="description" id="description" cols="30" rows="10" placeholder="Enter Description" class="form-control"></textarea> </div> <div class="form-group"> <button class="btn btn-primary">Insert</button> </div> </form> </div> </div> <ul id="inserted_data"> </ul> </div> <script> function InsertViaAjax() { var form = $("#ajax-form-submit"); // Give the loading icon when data is being submitted $("#success").val('loading...'); var form_data = $("#ajax-form-submit").serialize(); $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content') } }); $.ajax({ type:"POST", url:"{{url('insert-ajax')}}", data : form_data, success: function(data) { $("#success").html('Inserted into database').delay(3000).fadeOut(); $("#inserted_data").append('<li>'+data.success.title+'</li>'); } }); // To Stop the loading of page after a button is clicked return false; } </script> <script src="https://code.jquery.com/jquery.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script> </body> </html> |
This is it, if you have any problem regarding this tutorial, you can contact us via contact page.
Leave a Reply