Home > Software engineering >  I'm making an dependent drop-down of countries states and cities in Laravel 9 using jQuery and
I'm making an dependent drop-down of countries states and cities in Laravel 9 using jQuery and

Time:10-26

I'm making an dependent drop-downn of countries states and cities in laravel using jQuery and Ajax. I'm doing it on localhost Xampp. First i use jQuery for country. when country change jQuery get value and send to Controller. But when i send value from RegistrationFormComponent to CountryStateCity Controller and try to show what value i get. I got an error ( POST http://127.0.0.1:8000/getstate 500 (Internal Server Error) ). i don't know why im getting this error.

Route:

Route::get('/register', [CountryStateCityController::class, 'getcountry']);
Route::POST('/getstate ', [CountryStateCityController::class, 'getstate']);

JQuery and Ajax

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

$(document).ready(function () {
  $('#country').change(function () {
    var cid = this.value;   //$(this).val(); we cal also write this.
    $.ajax({
      url: "getstate",
      type: "POST",
      datatype: "json",
      data: {
        country_id: cid,
      },
      success: function(result) {
        // if(cid == "success")
        //   alert(response);
          console.log(result);
      },
      errror: function(xhr) {
          console.log(xhr.responseText);
        }
      });
  });
});

Controller

class CountryStateCityController extends Controller
{
    public function getcountry() {
        $country = DB::table('countries')->get();
        $data = compact('country');
        return view('RegistrationForm')->with($data);
    }

    public function getstate(Request $request) {
        
        $state = State::where('countryid'->$cid)->get();
        return response()->json($state);
    }

    public function getcity() {
    }
}

I think i tryed every possible thing. But didn't work. Please tell me how can i get rid of this problem. And please also tell me how can i send data from component to controller using jquery and ajax and get value form controller and take data from database and send back to component.

CodePudding user response:

please check controller function

public function getstate(Request $request) {

 $state = State::where('countryid' `=` ,request->$countryid)->get();
    return response()->json($state);
}

CodePudding user response:

This is written incorrectly.

public function getstate(Request $request) {
        
        $state = State::where('countryid'->$cid)->get();
        return response()->json($state);
    }

It should look like this.

public function getstate(Request $request) {
        
        $state = State::where('countryid', '=', $request->country_id)->get();
        return response()->json($state);
    }
  • Related