Home > front end >  How to paginate query results using Laravel and jQuery
How to paginate query results using Laravel and jQuery

Time:10-17

I'm trying to convert this static query

$companiesFinal = Websites::query();

    if(!empty($request->searchWord)) {
        $companiesFinal->where('web_name', 'LIKE', '%' . $request->searchWord . '%');
        $companiesFinal->where('web_seo_url', 'LIKE', '%' . $request->searchWord . '%');
    }

    if(!empty($request->category)){
        if(is_array($request->category)) {
            foreach($request->category as $categ) {
                $companiesFinal->orWhere('web_category', 'LIKE', '%' . $categ . '%');
            }
        } else {
            $companiesFinal->where('web_category', 'LIKE', '%' . $request->category . '%');
        }
    }

    if(!empty($request->claimed)){
        if($request->claimed == "all") {} else {
            $companiesFinal->where('claimed', '=', $request->claimed);
        }
    }

    if(!empty($request->sortBy)) {
        if($request->sortBy == "newest") {
            $companiesFinal->orderBy('created_at', 'DESC');
        } elseif($request->sortBy == "oldest") {
            $companiesFinal->orderBy('created_at', 'ASC');
        }
    }

    $companies = $companiesFinal->paginate(7);
}

to an AJAX jQuery call, and here comes the confusing part. I've already tried to do that but unsuccessful.

I tried something like:

$.ajax({
    type: 'GET',
    url: '{{ url("/ajaxCall") }}',
    data: $("form").serialize(),
    success: function(response) {
        var websites = "";
        $.each(response.data, function(index, value) {
            websites = websites   "<div>... "   value.web_name   "......."   value.web_link   "...</div>";
        });
        $(".getResults").html(websites);
    },
    error: function(xhr, ajaxOptions, thrownError) {
        console.log(xhr.status);
        console.log(thrownError);
    }
});

of course when I tried that I've converted the controller query to return a JSON response, and other necessary stuff, but the result was the browser console saying "value not defined".

Also confusing for me is how I am gonna display Laravel pagination when getting this data with Ajax? I'll be so grateful if someone helps.

CodePudding user response:

According to the documentation, the data structure returned from Laravel when you use pagination into a JSON result looks like this:

{
   "total": 50,
   "per_page": 15,
   "current_page": 1,
   "last_page": 4,
   "first_page_url": "http://laravel.app?page=1",
   "last_page_url": "http://laravel.app?page=4",
   "next_page_url": "http://laravel.app?page=2",
   "prev_page_url": null,
   "path": "http://laravel.app",
   "from": 1,
   "to": 15,
   "data":[
        {
            // Record...
        },
        {
            // Record...
        }
   ]
}

So assuming this HTML structure:

<form>
  <!-- your search form ... --->
</form>
<div id="getResults"></div>
<div id="pages"></div>

I would use this kind of JavaScript:

function searchUrl(page) {
  return '{{ url("/ajaxCall") }}?'   $("form").serialize()   '&page='   page;
}

function showResult(page) {
  return $.get(searchUrl(page)).done(function (result) {
    // render result records
    $("#getResults").empty();
    result.data.forEach(function (record) {
      $("<div>... "   record.web_name   "......."   record.web_link   "...</div>").appendTo("#getResults");
    });

    // render pagination links
    $("#pages").empty();
    for (let p = 1; p <= result.last_page; p  ) {
      if (p === result.current_page) $('<span>'   p   '</span>').appendTo("#pages");
      else $('<a href="'   searchUrl(p)   '">'   p   '</a>').appendTo("#pages");
    }
  }).fail(function(xhr, status, thrownError) {
    console.error(xhr.status, thrownError);
  });
}

$(function () {
  $("form").submit(function (event) {
    event.preventDefault();
    showResult(1);
  });
});
  • Related