Why is responseText returning blank?

9.9k Views Asked by At

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?

3

There are 3 best solutions below

5
On BEST ANSWER
   $.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);

0
On

see jQuery.ajax, You are not using correct format, thats why response is blank.

Success handler will return the response from server end. So use it like :

 $.ajax({
      type:"GET",
      url: "includes/phpscripts.php?action=cords",
      type: "json"
      success : function(response){
               console.log(response);
        }
   });
0
On

The response is blank because the response is not returned from the server when that line of code was executed. Try to set the responseText inside ajax callback. See below,

var response = '';
var request = $.ajax({
  type:"GET",
  url: "includes/phpscripts.php?action=cords",
  type: "json"
}).done (function (data) {
   console.log(data); //json object as jquery converts it for you
   console.log(request.responseText); //string text as returned the server.
   response = request.responseText; 
   //^-- response is a string text as returned the server.
});

DEMO: http://jsfiddle.net/hUY6v/