Why is responseText returning blank?

Jason picture Jason · Jun 4, 2012 · Viewed 9.6k times · Source

I have a database table whose fields contain latitude and longitude coordinates of positions. I want to create markers for a Google Map view using the information from the database.

I've implmented the query function as

function getCords(){
  $link = connectDB();
  $query = "SELECT * FROM tour";
  $results = mysqli_query($link, $query);

  $jsonArray = array();
  while ($row = mysqli_fetch_assoc($results)){
    $jsonArray[] = array('fileName' => $row['FileName'], 'lat' => $row['Lat'], 'lon' => $row['Lon']);

  }

return json_encode($jsonArray);
}

When I call this function from a php page, it returns the usual JSON format.

My issue is executing an ajax query. I have the query function above in a php scripts file containing six or so utility functions controlling login, logout, registration and the like. To query the database via jquery, I tried

var request = $.ajax({
  type:"GET",
  url: "includes/phpscripts.php?action=cords",
  type: "json"
});

var response = request.responseText;

My problem is the response is always empty. Is this due to the formation of the URL or for some other reason?

Answer

thecodeparadox picture thecodeparadox · Jun 4, 2012
   $.ajax({
      type:"GET",
      url: "includes/phpscripts.php?action=cords",
      dataType: 'json', // necessary, because you're sending json from server
      success: function(response) {  // response will catch within success function
        console.log(response);
      }
    });

or

   var request = $.ajax({
      type:"GET",
      url: "includes/phpscripts.php?action=cords",
      dataType: 'json', // necessary, because you're sending json from server
    }).done(function(response) {
       console.log(response);
    });

NOTE

Instead of return json_encode($jsonArray);, use echo json_encode($jsonArray);