Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

hook's avatar
Level 1

Unable to Load AJAX Data to Dynamic Dependent Dropdown

I make a program to check shipping cost and used a dynamix dependent dropdown to retrieve province_id and city_id.AJAX successfully retrieved the data from the server, but when I tried to display the data on the selectbox, no change occurred. I have tried several ways to add data into the selectbox but still no change.

Here's my code

Controller :

public function getProvince(){
    $curl = curl_init();

    curl_setopt_array($curl, array(
        //
	   Curl configuration
		//
    ));

    $response = curl_exec($curl);
    $err = curl_error($curl);
    curl_close($curl);

    if ($err) {
        echo "cURL Error #:" . $err;
    } else {
        $response = json_decode($response, true);
        $province_data = $response['rajaongkir']['results'];
        return $province_data;
    }
}

public function getCity($province_id){
    $curl = curl_init();

    curl_setopt_array($curl, array(
        //
		Curl configuration
		//
        ),
    ));

    $response = curl_exec($curl);
    $err = curl_error($curl);
    curl_close($curl);

    if ($err) {
        echo "cURL Error #:" . $err;
    } else {
        $response = json_decode($response, true);
        // $data_sender = $response;
        $cities_data = $response['rajaongkir']['results'];
        return $cities_data;
    }
}

public function checkOut()
{
    $province = $this->getProvince();
    $cities = $this->getCity('province_id');
    return view('check-out', compact('province', 'cities'));
}

Route :

Route::get('/province', [CheckoutController::class, 'getProvince'])->middleware('auth');
Route::get('/city/{province_id}', [CheckoutController::class, 'getCity'])->middleware('auth');

View :

<div class="col-sm-4 mb-3">
  <p class="mb-0">Province</p>
    <select class="nice-select form-control" name="province" id="province">
       <option value="">None</option>
          @foreach ($province as $item)
              <option value="{{$item['province_id']}}">{{$item['province']}}</option>
          @endforeach
     </select>
     <input type="text" class="form-control" hidden nama="province_name" placeholder="Get province name">
     </div>


     <div class="col-sm-4 mb-3">
       <p class="mb-0">City</p>
         <select class="nice-select form-control" name="city" id="city">
            <option value="">None</option>
         </select>
         <input type="text" class="form-control" hidden nama="city_name" placeholder="Get city name">
      </div>

Ajax Script :

 $(document).ready(function () {
  $(document).on('change', '#province', function () {

      var province_id = $(this).val();
      $.ajax({
          dataType: 'json',
          type: 'get',
          url: '/city/'+province_id,
          data: {
              'province_id': province_id
          },

          success: function (data) {
              //  console.log('success');
               console.log(data);
              if (data) {
                  $("#city").empty();
                  $("#city").append('<option>Select Branch</option>');
                  $.each(data, function (key, value) {

                      $("#city").append('<option value="' + value[
                              "city_id"] + '">' + value["city_name "] +
                          '</option>');
                  });
              }
          },
          error: function () {
              console.log('fail');
              alert("fail");

          }
      });
  });
 });

Ajax ressponse :

  0 : 
     city_id: "106"
	 city_name: "Cilegon"
	 postal_code: "42417"
	 province: "Banten"
	 province_id: "3"
	 type: "Kota"
	 [[Prototype]]: Object

  1 : 
	 city_id: "232"
	 city_name: "Lebak"
	 postal_code: "42319"
	 province: "Banten"
	 province_id: "3"
	 type: "Kabupaten"
	 [[Prototype]]: Object

  2 :  
	 city_id: "331"
	 city_name: "Pandeglang"
	 postal_code: "42212"
	 province: "Banten"
	 province_id: "3"
	 type: "Kabupaten"
	 [[Prototype]]: Object

 3 : 
	city_id: "402"
	city_name: "Serang"
	postal_code: "42182"
    province: "Banten"
	province_id: "3"
	type: "Kabupaten"
    [[Prototype]]: Object
0 likes
8 replies
Snapey's avatar

So what happens? You can see if the request is made, if the json is returned.

You can inspect the dom element to see if it changes. You could manually call the same code as you have in your success function to see if the options are added to the select input.

Its so much easier to debug in the browser than sat here looking at static code

1 like
hook's avatar
Level 1

@Snapey, thanks for the response

 You could manually call the same code as you have in your success function to see if the options are added to 
 the select input.

I have manually called the same code in success function but still no option is added.

Then I tried the chosen.jsm plugin, all the data could appear as expected but a new problem arose, there was a duplication of selectboxes, one bootstrap selectbox (original) and the other selectbox from chosen.js, as information also data only appears in the selectbox from chosen.js, not the original selectbox (remains empty). Of course I have imported the cdn of chosen.js. If only I could add an image to make the problem clearer

gych's avatar

So you console log console.log(data); is returning the expected data?

I see a typo in your code, you added value["city_name "] with a space after city_name instead of value["city_name"]

Corrected part:

  $("#city").append('<option value="' + value["city_id"] + '">' + value["city_name"] +  '</option>');
1 like
hook's avatar
Level 1

@gych

Yup, it returns the expected data, I have also corrected the typo but the data still won't display in the selectbox, and thanks in advance

gych's avatar

@hook Is the option Select City added or is it also not showing as select option?

gych's avatar

@hook Update return $cities_data in your controller to

return response()->json($cities_data);
amitsolanki24_'s avatar

@hook Try to console.log(key, value) in each function

Or try to change dataType: 'json' to type: 'json'

Please or to participate in this conversation.