Blog de programación, errores, soluciones

Using JQuery AJAX in Laravel

In this article we will touch on how to make a POST request with JQuery ajax in laravel ($.ajax). This also works for put, patch and delete.

Creating a route for the controller

The First thing we have to do is create a route that will be the response to our AJAX request.

routes/web.php
Route::post('miJqueryAjax','AjaxController@index');

Create the controller

Now we create the AjaxController, and add the following code

app/Http/Controllers/AjaxController.php
<?php 
namespace App\Http\Controllers;
use Illuminate\Http\Request;
 class AjaxController extends Controller {
     /**
      * Display a listing of the resource.
      *
      * @return \Illuminate\Http\Response
      */
     public function index()
     {
         echo "im in AjaxController index";//simplemente haremos que devuelva esto
     }
 } 

If you are doing this from scratch you maybe need to create a route like this one:

routes/web.php
Route::post('/', function () {
   return view('master');
});

Create a view called “master”

On folder resource/views we’ll create master.blade.php with the following lines, comments gives you some indications where to put some code fragments so take it in consideration.

resources/views/master.blade.php
<!DOCTYPE html>
 <html>
    <head>
       <title>this is my mater page</title>
       <style></style>
       //aqui ira meta token
    </head>
    <body>
       <article>
        <header>
            <h1>this is my master page</h1>
        </header>
        <main>
        </main>
        <footer>
            Ejemplo propuesto en blastcoding.com
        </footer>
       <article>
       //pondre todos los script antes de cerrar la etiqueta body
       <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
       //(english) copy $.ajaxSetup here
       //(english) copy $.ajax code here    </body>
</html> 

Remember that in this post we want to use ajax with post method so the example is simplest possible.

Adding token to all header request

After the JQuery CDN create an script with the following code, thos will take the token value and added to headers to be passed in a future request.

asegurate que el código es global
$.ajaxSetup({
     headers: {
         'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')     
     }
 }); 

Now we need our script jQuery using ajax to send data, in this case json {‘name’:’luis’}

resources/views/master.blade.php[Evento on click]
$('#myajax').click(function(){
       //we will send data and recive data fom our AjaxController
       $.ajax({
          url:'miJqueryAjax',
          data:{'name':"luis"},
          type:'post',
          success: function (response) {
                      alert(response);
          },
          statusCode: {
             404: function() {
                alert('web not found');
             }
          },
          error:function(x,xs,xt){
              //nos dara el error si es que hay alguno
              window.open(JSON.stringify(x));
              //alert('error: ' + JSON.stringify(x) +"\n error string: "+ xs + "\n error throwed: " + xt);
          }
       });
});

Finally, after add meta tag, the jquery ajaxsetup and our script to use ajax that trigger on click event our view it would be as follows:

resources/views/master.blade.php
<!DOCTYPE html>
 <html>
    <head>
         <title>this is my mater page</title>
         <style></style>
         <meta name="csrf-token" content="{{ csrf_token() }}">
    </head>
    <body>
         <article>
             <header>
                    <h1>this is my master page</h1>
             </header>
             <main>
                 <button id='myajax'>click me</button>
             </main>
             <footer>
 </footer>
         </article>
       {{--all my scripts goes here--}}
       <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
       <script type = "text/javascript">
         $.ajaxSetup({
             headers: {
                 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
             }
         });
         $('#myajax').click(function(){
            //we will send data and recive data fom our AjaxController
            //alert("im just clicked click me");
            $.ajax({
               url:'miJqueryAjax',
               data:{'name':"luis"},
               type:'post',
               success:  function (response) {
                  alert(response);
               },
               statusCode: {
                  404: function() {
                     alert('web not found');
                  }
               },
               error:function(x,xs,xt){
                  window.open(JSON.stringify(x));
                  //alert('error: ' + JSON.stringify(x) +"\n error string: "+ xs + "\n error throwed: " + xt);
               }
            });
             });
       </script>
    </body>
 </html>
Somethig wrong? If you found an error or mistake on the content you can contact me on twitter | @luisg2249_luis.
Last 4 post in same category