filter cities by state in Laravel with Javascript?

Asked

Viewed 46 times

-1

I have a city and a state camp, I would like when click on the field and select a certain state, in the city options appear only the cities related to that specific state. it is in my local environment - in Xampp and Mysql.

inserir a descrição da imagem aqui

I was able to list the states on the cosole when I click on it according to the scrupt line, but we couldn’t call the route.

<script>
     $('#id_state').on('change', function(e){
         var id_selected_state = e.target.value;
         console.log(id_selected_state);

         $.get('/citiesByState/' + id_selected_state, function(data){ 
             
        });
 </script>

The route I am developing this way, but gives error and does not call the controller to execute the function.

Route::get('citiesByState/{id_selected_state}', 'CitiesController@citiesByState')->name('citiesByState');

That was the controller I developed.

<?php

namespace App\Http\Controllers;
use Illuminate\Support\Facades\Auth;
use App\Helpers;
use App\Models\City;

class CitiesController extends Controller
{
    public function citiesByState($id_selected_state)
    {
     $cities = City::where('id_state', '=', $id_selected_state)->get();

     return $cities;

    }

}

I use only WEB routes, I am not able to call the route from javascript, to return only the cities of that selected state.

The mistake is this. inserir a descrição da imagem aqui

If anyone can help me with solving the route error. Thank you

  • your server is running at which address: type (localhost:8080) or localhost as demonstrated in the image? is not it? also avoid putting name of lowercase wheels put the name all in lowercase

  • This on localhost

  • error is not found.

  • it is not finding. I am unable to create a route to get the data from java script.

1 answer

-1


One solution I see is to make a POST request with Ajax, something like that:

 $.ajax({
      "url": "{{ route('citiesByState') }}",
      type: "POST",
      data: { id_selected_state: id_selected_state },
      headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
      },
      success: function (data) {
        //alterar lista de estados do select
      },
 });

And you would need to change your route to receive POST requests:

Route::post('citiesByState', 'CitiesController@citiesByState')->name('citiesByState');

Browser other questions tagged

You are not signed in. Login or sign up in order to post.