Send a php array to the AJAX response

advertisements

I am trying to filter state, zones of Nepal using ajax. I have got them in MySQL database.

I have populated zone select box initially, it is okay.

<select class="district col-md-3 center-block" id="zone">
<?php
    while ($res = mysqli_fetch_assoc($result_zones)) {
        echo "<option value='".$res['name']."'>".$res['name']."</option>";
    }
?>
</select>

Now What I am trying is when user changes zone, I need all districts associated with this zone from districts table.

What I have done is here:

Ajax call

<script>
        $(document.body).on("change","#zone",function(){
            //console.log(this.value);
            $.ajax({
                dataType : 'json',
                async: false,
                url:'process.php?zone_id=' + this.value,
                complete: function (response) {
                    var result = JSON.stringify(response.data);//parsing status from response received from php
                    console.log(result);
                }
               });
        });
</script>

process.php

<?php
    if (isset($_GET['zone_id'])) {
      $arr =array();
      $zone_id=$_GET['zone_id'];
      $i=0;
      $result = mysqli_query($dbconfig,"SELECT * FROM districts WHERE zone_id = '$zone_id'");
      while ($row = mysqli_fetch_assoc($result)) {
        $arr[$i] = $row;
        $i++;
      }
      // preparing correct format for json_encode
      header('Content-type: application/json');
      echo json_encode(array('data' => $arr)); //sending response to ajax
    }
 ?>

When I go through url http://localhost/nepal-locations/process.php?zone_id=8, I'm getting data as I need like below:

{"data":[{"id":"42","name":"Mustang","zone_id":"8"},{"id":"43","name":"Myagdi","zone_id":"8"},{"id":"44","name":"Parbat","zone_id":"8"},{"id":"45","name":"Baglung","zone_id":"8"}]}

But I'm getting data empty in console.

{data: []}
data
:
[]

What might be wrong I'm doing?

Update: output console.log(response)


You are getting empty array because you are passing name instead of id

change your <select> as below:

<select class="district col-md-3 center-block" id="zone">
<?php
    while ($res = mysqli_fetch_assoc($result_zones)) {
        echo "<option value='".$res['id']."'>".$res['name']."</option>"; //<-----Add id instead of name
    }
?>
</select>