0

I’m working with Edamam API and I was able to load the first page. Now I’d like to load the next page. I have added the infinite scroll but it is loading the same first-page result over and over again.

This is my AJAX;

ajax: {
        theme: 'bootstrap',
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        url: "{{ route('searchFoodAPI') }}",
        type: "post",
        dataType: 'json',
        data: function (params) {
            return {
                search: params.term,
                page: params.page
            };
        },
        processResults: function (response, params) {
            params.page = params.page || 1;

            return {
                results: response.results,
                pagination: {
                    more: params.page
                }
            };
        },
        cache: true
        },
        placeholder: 'Search for Ingredient',
        minimumInputLength: 2,
    });

As per the Select2 documentation regarding the pagination.

Select2 will expect a pagination.more value in the response. The value of more should be true or false, which tells Select2 whether or not there are more pages of results available for retrieval:

But my JSON response provided "_links" object.

"_links" => array:1 [
"next" => array:2 [
  "title" => "Next page"
  "href" => "https://api.edamam.com/api/food-database/v2/parser?session=44&ingr=oil&app_id=******&app_key=******&nutrition-type=cooking"
]

]

This is what is in my Controller now, getting the $link object.

            $data = (string) $response->getBody();
            $decoded_json = json_decode($data, true);
            $hints = $decoded_json['hints'];
            $links = $decoded_json['_links'];

            $link = $links['next']['href'];

            $responseArray = array();
            foreach ($hints as $hint) {
                $responseArray[] = array(
                    "id" => $hint['food']['foodId'],
                    "text" => $hint['food']['label']
                );
            }

            $results = array(
                "results" => $responseArray,
                "page" => $link
            );

            return response()->json($results);

I’ve checked the entire Select2 documentation and found nothing using the URL provided by JSON response to load the next page results.

Trying to figure this out for 2 weeks.....

Is there any way to add a button for “PREV” and “NEXT”? With these buttons, I can easily assign the target URL. But if yes, how to initialize the results without reloading the page? If none, how can I load the next page results using the URL?

iAmBorgy
  • 73
  • 9

0 Answers0