skip to Main Content

I am trying to fetch a list of cities that has more than 40,000 cities, My issue is how to optimize since my browser keeps being responsive when loading the cities.
In Laravel Controller I have,

public function getCities(Request $request)
    {   
   $query = $request->input('query');
    $cities = UsCities::where('CITY', 'like', '%' . $query . '%')->get()->pluck('CITY')->toArray();
    return response()->json($cities);
    }

and the ajax code

$.ajax({
        method: "GET",
        url: '{{ route("get.cities")}}',
         data: { query: $('#city-selected').val() },
        success: function (response) {
          townsTags = response;
          startAutocomplete(townsTags, "#city-selected");
        }
      });
    function startAutocomplete(availableTags, inputSelector) {
      $(inputSelector).autocomplete({
        source: availableTags
      });
    }

2

Answers


  1. If you want to optimize your search method when users type the city in the input field, you need to make the condition in your JS with the following:

    1. Start the ajax only after the input character is more than x length. That way the SQL query will return more accurate data.
    2. Start the ajax only after y milliseconds so that http request will not always execute, thus only execute when needed.

    Below is the code that you can try:

    $(document).ready(function() {
      // create a timer variable for setTimeout
      var inputTimer;
      function handleInputChange() {
        $('#loading').show(); // much better add a loading somewhere so that users can see that something is happening
    
        // clear the timer variable for setTimeout
        clearTimeout(inputTimer);
        var cityVal = $(this).val();
    
        // start ajax when input is 3 or more character length so that it will not always submit a request to your backend
        if (cityVal.length >= 3) {
    
          // setTimeout so that it will only execute the ajax after 500 miliseconds where there is no more incoming changes
          inputTimer = setTimeout(function() {
            // swap console.log to your ajax
            console.log("Input value changed:", cityVal);
            $('#loading').hide(); // add inside 「success」 method of ajax so that loading will hide after executing irregardless of success or error
          }, 500);
        } else {
          console.log("please enter at least 3 characters")
        }
      }
      $('#city-selected').on('input', handleInputChange);
    });
    

    change 3 or 500 depending on when you want to start the execution.

    Login or Signup to reply.
  2. You may use Eloquent ORM: API Resources with collections in controller.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search