1

Problem : I am trying to populate the 1st SELECT on load. And 2nd SELECT depends on the 1st one.
1st select : populated with states
2nd select : should be populated with districts based on selected states.
jSON file is HERE
Solutions given on other stackoverflow documents didn't meet my requirements\

$(document).ready(function(){
  $.ajax({
    type:'GET',
    header:{' Access-Control-Allow-Origin ':'*'},
    datatype:'json',
    url:'https://github.com/sab99r/Indian-States-And-Districts/blob/master/states-and-districts.json'
  })
  .done(function(response){
    console.log(response);
  })
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Demo</title>
  </head>
  <body>
    <div class="">
      <select class="states" >
      </select>
      <select class="districts" >
      </select>
    </div>
    <link rel="text/script" href="jquery-3.5.1.js">
    <link rel="text/>script" href="index.js">
  </body>
</html>

3
  • 1
    when your first select's result is ready( jQuery success function) , go for second request Commented Feb 3, 2021 at 8:31
  • can you please elaborate. i am not getting you. are u saying to add success attribute after the url inside ajax ? Commented Feb 3, 2021 at 9:03
  • 1) you load json 2) when that json has finished loading, you then populate the select. "when the json has loaded" is the "jquery success function" - in your code that's inside done Commented Feb 3, 2021 at 9:06

3 Answers 3

2

Below example show an example how to load data, first and then store it in a var to prevent ajax loading every change, then in every change fetch data array to load districts :

( uring raw url load text , so you have to pare json from string at first )

See wokring snippet :

data = [];

$(document).ready(function() {

  $(".states").on("change", stateChange);

  $.ajax({
      type: 'GET',
      header: {
        ' Access-Control-Allow-Origin ': '*'
      },
      datatype: 'json',
      url: 'https://raw.githubusercontent.com/sab99r/Indian-States-And-Districts/master/states-and-districts.json'
    })
    .done(function(response) {
      var resp = JSON.parse(response);
      loadStates(resp);
    })

});


var loadStates = function(response) {

  if (response.states) {
    data = response.states;

    response.states.forEach(state => {

      var option = $('<option/>');
      option.attr({
        'value': state.state,
      }).text(state.state);
      $('.states').append(option);
    })
  }
}

var stateChange = function(event) {
  let stateValue = event.target.value;
  let state = data.find(state => state.state === stateValue);
  
  $('.districts').html("");

  if (state) {

    state.districts.forEach(ditrict => {
      var option = $('<option/>');
      option.attr({
        'value': ditrict,
      }).text(ditrict);
      $('.districts').append(option);
    })

  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
state :
<select class="states">
</select>
<br> distric
<select class="districts">
</select>

Sign up to request clarification or add additional context in comments.

3 Comments

In case if i am loading a local json file. Then i need not to parse . right /
no it depends on the datatype return by your server , because here from github , it returned text/plain , so you have to return application/json from server then use without parse
yes. As you told i changed it to application/json and it's working fine. thanks
0

Just set code according to your requirement but you need to set all logic. You need to set when you send state data then you will get all districts

function changeselect(){
$.ajax({
    type:'GET',
    header:{' Access-Control-Allow-Origin ':'*'},
    datatype:'json',
    url:'https://github.com/sab99r/Indian-States-And-Districts/blob/master/states-and-districts.json'
  })
  .done(function(response){
    console.log(response);
    response.foreach(function(data){
    $("#distr").append("<option>+data+</option>")
    })
  })
}
$(document).ready(function(){
  $.ajax({
    type:'GET',
    header:{' Access-Control-Allow-Origin ':'*'},
    datatype:'json',
    url:'https://github.com/sab99r/Indian-States-And-Districts/blob/master/states-and-districts.json'
  })
  .done(function(response){
    console.log(response);
    response.foreach(function(data){
    $("#distr").append("<option>+data+</option>")
    })
  })
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Demo</title>
  </head>
  <body>
    <div class="">
      <select class="states" onchange="changeselect()">
      <option>A</option>      
      <option>B</option>      
      <option>C</option>


      </select>
      <select class="districts" id="distr">
      </select>
    </div>
    <link rel="text/script" href="jquery-3.5.1.js">
    <link rel="text/>script" href="index.js">
  </body>
</html>

1 Comment

@jeno if it work please accept my answer Thank you
0

I have got a even short code to do it.
We can use ajax GET to get data from the raw of any repository.
Solution to the above question :

$.get('https://raw.githubusercontent.com/aps08/web-development/main/web-dev-series/JSON/indian-states-and-cities.json',  // url
        function (data1, textStatus, jqXHR) {  // success callback
          var data1 = JSON.parse(data1);
          load(data1);
      });

Remember that if u loading data from your local machine then you need to remove
var data1 =JSON.parse(data1) line

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.