Send the result of the PHP request via JSON

advertisements

I am trying to send a Query result as JSON but when i use console.log it shows empty result.

PHP Code:

 function getCountries($countries){
    $sql = mysqli_query($connection, 'SELECT DISTINCT id, type, level, code, name, durations FROM destinations where gateway_code="YBG" ORDER BY name' );
      while($row = mysqli_fetch_array($sql))
      {
         echo json_encode($row); // I have doubt here, i want to send complete Query result as JSON

      }
      exit();
  } 

  $abc = $_POST['countries'];
  getCountries($abc);

Ajax [Sending data works fine but response not working):

$(document).ready(function(){
  var $leavingFrom = $('#select-leaving-from');
  $leavingFrom.on('change', function() {
  var $city_code = this.value;
  loadDepartures($city_code);
 });
});

function loadDepartures($cityname){
 var dataString = $cityname;
 $(document).ready(function(){
 jQuery.ajax({
 type: "POST",
 url: 'get_data.php',
 datatype: 'json',
 data: {'countries': dataString},
 success: function (output, textStatus) {
                console.log(output);
        }
   });
 });
}

The only issue is that i am unable to send JSON data (Query Result) to Ajax back. Need suggestions


You are outputting invalid JSON (well, valid JSON, multiple times, creating an invalid JSON string, if that makes sense). You need to build the entire array, then JSON encode it:

$rows = array();
while($row = mysqli_fetch_array($sql))
{
    $rows[] = $row;
}
echo json_encode($rows);
exit();