Chose Language:
comments
Author: Admin/Publisher |finished | checked

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.

Before continue with this topic please check that your JQuery is working properly on Laravel, if not read Laravel Frontend

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.

Take in consideration that laravel 8 changes how we make routes to controllers so check your Laravel version first and use one of the following routes:

before Laravel 8 routes/web.php
Route::post('miJqueryAjax','AjaxController@index');
Laravel 8 or supirior routes/web.php
use App\Http\Controllers\AjaxController;
Route::post('miJqueryAjax',[AjaxController::class,'index']);

You may need to run dump-autoload, remember that we are using use:

(project-folder)
composer dump-autoload

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>

Important: the above example was made assuming that you know how to use Ajax with jQuery, so it doesn’t explain how to use the .ajax function at all, just used it. Maybe I create a new post explaining this in the future.

In case that you return a different data type in jQuery than the default one, use datatype to specify what data type is, here is a list of different data types that jquery.ajax admits:

dataType

  • default( no datatype specify): Intelligent Guess (xml, json, script, or html) jQuery will try to infer it based on the MIME type of the response
  • “xml”
  • “html”
  • “script”
  • “json”
  • “jsonp”
  • “text”
  • “text xml” – text that would be interpreted as XML
  • “json text xml”
  • “json xml”
Category: en-javascript
Something wrong? If you found an error or mistake in the content you can contact me on Twitter | @luisg2249_luis.
Last 4 post in same category

Comments