This is the PART – 2 for the Laravel CRUD using jQuery AJAX, If you did not read the PART – 1, please click here to read it first.

Create User Interface.

For the layout purpose I uses the bootstrap and font awesome for the displaying icon on screen. So first place all the required CSS and jQuery file inside the public folder of the project.

Now let’s create the new file named “layout.blade.php” inside the resources->views folder.

Now change the code of that file with the following code.

File Name : layout.blade.php

<!DOCTYPE HTML> <html> <head> <title>@yield('title') - Laravel CRUD</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="keywords" content="" /> <link href="{{ asset('css/bootstrap.min.css') }}" rel='stylesheet' type='text/css' /> <link href="{{ asset('css/style.css') }}" rel='stylesheet' type='text/css' /> <link href="{{ asset('css/font-awesome.css') }}" rel="stylesheet"> <script src="{{ asset('js/jquery.min.js') }}"> </script> </head> <body> <div id="wrapper"> @yield('content') </div> <script src="{{ asset('js/bootstrap.min.js') }}"> </script> </body> </html>

Now create the new file named “CRUD.blade.php” inside the resources->views folder and replace the code of that file with the following code.

File Name : CRUD.blade.php

@extends('layout') @section('title', 'Laravel CRUD with jQuery AJAX') @section('content') <style> .form-horizontal{ margin: 10px; background-color: none !important; } body{ background-color: #FFFFFF !important; } </style> <script> $(document).ready(function() { var btnAdd = $("#btnAdd"); var btnClear = $("#btnClear"); var divError = $("#divError"); var txtBookName = $("#txtBookName"); var txtAuthorName = $("#txtAuthorName"); var csrfToken = $("input[name='_token']"); var tblData = $("#tblData"); var updateURL = "{{ asset('/Update') }}"; var deleteURL = "{{ asset('/Delete') }}"; btnAdd.click(function() { var bookName = txtBookName.val(); var authorName = txtAuthorName.val(); if(bookName == "" || authorName == "") { divError.html("Please, Enter all details!!!"); } else { var data = { _token : csrfToken.val(), txtBookName : txtBookName.val(), txtAuthorName : txtAuthorName.val()}; $.post("{{ url('/AddBook') }}",data) .done(function(result) { txtBookName.val(""); txtAuthorName.val(""); divError.html(result); DisplayTable(); }) .fail(function(result) { divError.html("Sorry, Something goes wrong!!!"); }); } }); btnClear.click(function() { txtAuthorName.val(""); txtBookName.val(""); divError.html(""); }); function DisplayTable() { var data = { _token : csrfToken.val() }; $.get("{{ url('/AllBooks') }}", data) .done(function(result) { if(result instanceof Array) { tblData.html(""); tblData.append($("<tr></tr>") .append(Create("<th></th>","ID")) .append(Create("<th></th>","Book Name")) .append(Create("<th></th>","Author Name")) .append(Create("<th></th>","Update")) .append(Create("<th></th>","Delete"))); for(var i = 0;i<result.length;i++) { tblData.append($("<tr></tr>") .append(Create("<td></td>",result[i]["ID"])) .append(Create("<td></td>",result[i]["BookName"])) .append(Create("<td></td>",result[i]["AuthorName"])) .append(Create("<td></td>","<a href='"+updateURL+"/"+result[i]["ID"]+"'><i class='fa fa-edit'></i></a>")) .append(Create("<td></td>","<a href='"+deleteURL+"/"+result[i]["ID"]+"'><i class='fa fa-remove'></i></a>"))); } } }) .fail(function(result) { divError.html(result.responseText); }); } function Create(type, text) { return $(type).html(text); } DisplayTable(); }); </script> <form class="form-horizontal"> {!! csrf_field() !!} <div class="form-group" style="text-align:center;color:red;" id="divError"> </div> <div class="form-group"> <label for="txtBookName" class="col-sm-2 control-label">Book Name</label> <div class="col-sm-10"> <input type="text" class="form-control" id="txtBookName" placeholder="Book Name"> </div> </div> <div class="form-group"> <label for="txtAuthorName" class="col-sm-2 control-label">Author Name</label> <div class="col-sm-10"> <input type="text" class="form-control" id="txtAuthorName" placeholder="Author Name"> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="button" class="btn btn-primary" id="btnAdd">Add</button> <button type="reset" class="btn btn-default" id="btnClear">Clear</button> </div> </div> </form> <br/> <table class="table table-hover table-bordered table-striped" id="tblData"> </table> @endsection

Above code will allow us to create the new book and display all the book on the page.

Run the project you will get the below screen,

Now add the book name and author name and click on the Add button to create the book, After click on the add button it will display the success message if the book was successfully add to the table, otherwise it will display the error message on the top of the page.

If will also display that book details on that same page.

Not what we done so far, How the Laravel accepted the AJAX request ?

Laravel can not accept any post or get request with out the csrf_field, csrf_field is token that will help the Laravel to identify the request is come from it’s our website or from any other website, If the request come without the csrf_field than request was denied by the laravel.

It means every request sent to the Laravel framework we also have to pass the csrf_field value.

How can we get the csrf_field value?

So for that we have to the write the following line of code inside the form the tab.

{!! csrf_field() !!}

It will generate the one hidden field where we place this line of code, the name of the hidden field was _token.

As you seen in above image it will create that hidden field with the some value, So you have to now send that value with the name field _token to every request. So Laravel will accept your request and forward that your request to specific action method.

jQuery AJAX request to insert the record.

So first we have to find that csrf_field and have to get that value, So below code will help us to find the csrf_field and it’s value. After that I created one object with some values that I have to send to the server and I also added the csrf_field value to that object with the name _token.

var csrfToken = $("input[name='_token']"); btnAdd.click(function() { var data = { _token : csrfToken.val(), txtBookName : txtBookName.val(), txtAuthorName : txtAuthorName.val()}; $.post("{{ url('/AddBook') }}",data) .done(function(result) { txtBookName.val(""); txtAuthorName.val(""); divError.html(result); DisplayTable(); }) .fail(function(result) { divError.html("Sorry, Something goes wrong!!!"); }); });

Please does not add the above code in any files it is already add in the CRUD.blade.php file.

Now I hope you understand that how we can send the request to the Laravel framework using the jQuery AJAX.

So now I will provide you the remaining code for the Update and delete.

File Name : update.blade.php

@extends('layout') @section('title', 'Laravel CRUD with jQuery AJAX') @section('content') <style> .form-horizontal{ margin: 10px; background-color: none !important; } body{ background-color: #FFFFFF !important; } </style> <script> $(document).ready(function() { var btnAdd = $("#btnAdd"); var btnClear = $("#btnClear"); var divError = $("#divError"); var txtBookName = $("#txtBookName"); var txtAuthorName = $("#txtAuthorName"); var csrfToken = $("input[name='_token']"); var tblData = $("#tblData"); var id = "{{ $data->ID }}"; btnAdd.click(function() { var bookName = txtBookName.val(); var authorName = txtAuthorName.val(); if(bookName == "" || authorName == "") { divError.html("Please, Enter all details!!!"); } else { var data = { _token : csrfToken.val(), txtBookName : txtBookName.val(), txtAuthorName : txtAuthorName.val(), ID : id }; $.post("{{ url('/Update') }}",data) .done(function(result) { divError.html(result); }) .fail(function(result) { divError.html("Sorry, Something goes wrong!!!"); }); } }); btnClear.click(function() { document.location = "{{ url('/') }}"; }); }); </script> <form class="form-horizontal"> {!! csrf_field() !!} <div class="form-group" style="text-align:center;color:red;" id="divError"> </div> <div class="form-group"> <label for="txtBookName" class="col-sm-2 control-label">Book Name</label> <div class="col-sm-10"> <input type="text" class="form-control" id="txtBookName" placeholder="Book Name" value="{{ $data->BookName }}" > </div> </div> <div class="form-group"> <label for="txtAuthorName" class="col-sm-2 control-label">Author Name</label> <div class="col-sm-10"> <input type="text" class="form-control" id="txtAuthorName" placeholder="Author Name" value="{{ $data->AuthorName }}"> <input type="hidden" class="form-control" id="txtAuthorName" placeholder="Author Name" value="{{ $data->ID }}"> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="button" class="btn btn-primary" id="btnAdd">Update</button> <button type="reset" class="btn btn-default" id="btnClear">Go Back</button> </div> </div> </form> <br/> </table> @endsection

File Name : delete.blade.php

@extends('layout') @section('title', 'Laravel CRUD with jQuery AJAX') @section('content') <style> .form-horizontal{ margin: 10px; background-color: none !important; } body{ background-color: #FFFFFF !important; } </style> <script> $(document).ready(function() { var btnAdd = $("#btnAdd"); var btnClear = $("#btnClear"); var divError = $("#divError"); var txtBookName = $("#txtBookName"); var txtAuthorName = $("#txtAuthorName"); var csrfToken = $("input[name='_token']"); var tblData = $("#tblData"); var id = "{{ $data->ID }}"; btnAdd.click(function() { var bookName = txtBookName.val(); var authorName = txtAuthorName.val(); if(bookName == "" || authorName == "") { divError.html("Please, Enter all details!!!"); } else { var data = { _token : csrfToken.val(), ID : id }; $.post("{{ url('/Delete') }}",data) .done(function(result) { window.location = "{{ asset('/') }}"; }) .fail(function(result) { divError.html("Sorry, Something goes wrong!!!"); }); } }); btnClear.click(function() { document.location = "{{ url('/') }}"; }); }); </script> <form class="form-horizontal"> {!! csrf_field() !!} <div class="form-group" style="text-align:center;color:red;" id="divError"> </div> <div class="form-group"> <label for="txtBookName" class="col-sm-2 control-label">Book Name</label> <div class="col-sm-10"> <input type="text" class="form-control" id="txtBookName" placeholder="Book Name" value="{{ $data->BookName }}" readonly="readonly"> </div> </div> <div class="form-group"> <label for="txtAuthorName" class="col-sm-2 control-label">Author Name</label> <div class="col-sm-10"> <input type="text" class="form-control" id="txtAuthorName" placeholder="Author Name" value="{{ $data->AuthorName }}" readonly="readonly"> <input type="hidden" class="form-control" id="txtAuthorName" placeholder="Author Name" value="{{ $data->ID }}"> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="button" class="btn btn-danger" id="btnAdd">Delete</button> <button type="reset" class="btn btn-default" id="btnClear">Go Back</button> </div> </div> </form> <br/> </table> @endsection

Main Points:

Laravel framework needs the csrf_field value with the every request comes form the client. csrf_field is hidden field with the some value, which helps the Laravel to identify the current request is valid or not. You have to use the {!! csrf_field() !!} place this line of code to generate the csrf_field. It will create the hidden field with _token name. While sending the request with jQuery AJAX you have to append this field with another data, and you must be have to send this field, other wise label framework denied your request. In the data object which you want to send to the server with jQuery AJAX, you must be have to provide the _token name field with the csrf_field value.

I hope you enjoyed this article, Please comment down your reviews about this.

Happy Coding...

🙂