Raphael Maycon
Raphael Maycon

Reputation: 73

Ajax Pagination Laravel 5.1

I'm trying to make a pagination with ajax and laravel 5, but I can not do the ajax works even with simple tests:

$(document).on('ready',function(){
$('.pager a').on('click', function (e) {
var page = $(this).attr('href').split('page=')[1];
         e.preventDefault();
            $.ajax({
          type: "GET",
          url: 'testeserver.php',
         //url:"raphael.dev/testeserver.php",
         dataType: 'json', // Notice! JSONP <-- P (lowercase)
         success:function(json){

             alert("Success"+json);
         },
         error:function(){
             alert("Error");
         }      
      });
    });
});

In this example I try one have a return on json ,

  <?php
$arr = array("element1","element2",array("element31","element32"));
$arr['name'] = "response";
echo $_GET['callback']."(".json_encode($arr).");";
?>

but only with the error alert , in fact I'm trying with these following cases :

BlogController:

  public function index(Request $request){
          $artigos = Artigo::where('publicado_em', '<=', Carbon::now())
            ->orderBy('publicado_em', 'desc')
            ->paginate(config('blog.artigos_por_pagina'));


        if ($request->ajax()) {
            return Response::json(view('Blog.artigos', compact('artigos'))->render());
        }
        return view('Blog.index', compact('artigos'));
    }

routes.php

post('/', 'BlogController@index');
get('/', 'BlogController@index');
get('/{slug}', 'BlogController@show');

jquery

$(document).on('ready',function(){
$('.pager a').on('click', function (e) {
var page = $(this).attr('href').split('page=')[1];
         e.preventDefault();
            $.ajax({
          type: "POST",
          url: 'page=' + page,
         dataType: 'json',
         success:function(json){

             alert("Success"+json);
         },
         error:function(){
             alert("Error");
         }      
      });
    });
});

Upvotes: 2

Views: 2770

Answers (2)

Raphael Maycon
Raphael Maycon

Reputation: 73

Just found the solution, changed my jquery code to :

$(document).on('ready',function(){
$('.pager a').on('click', function (e) {
          var page = $(this).attr('href').split('page=')[1];
          e.preventDefault();
          var url = '?page=' + page; 
$.post( url, function(data) {
        alert( "success"+data );
      })
        .done(function() {
          alert( "second success" );
        })
        .fail(function() {
          alert( "error" );
        })
        .always(function() {
          alert( "finished" );
      });

And found a error in my BlogController :

in

 if ($request->ajax()) {
 return Response::json(view('Blog.artigos', compact('artigos'))->render());
    }

the Facade Response was not declared, so just added

Use Request;

at the top,

but i still dont understand why the $ajax() dosent work, just the $get and $post

Upvotes: 1

jakehallas
jakehallas

Reputation: 2506

Laravel protects your application with CSRF tokens. When utilising Ajax you need to be sure to send across the CSRF token, otherwise Laravel will not process the request to protect your app.

$.ajax({
    url: 'test',
    type: "post",
    data: {'_token': $('input[name=_token]').val()},
    success: function (data) {
        alert('the joys'); 
    },
    complete: function (data) {

    }
});

Notice the $('input[name=_token]').val() - that will send your CSRF token. You will of course need to create a hidden input with the CSRF token in your view.

More information can be found here!

Upvotes: 0

Related Questions