I use ajax to get the number of rows (COUNT(*)) from a sql query in php.
The JSON return in Firefox-Network tab is:
[{"number":2}],
(the 2 is without quotes).
But in "ajax success" , when i try to get the value (2) from data[0]["number"] or data.length,it returns "undefined".
It works only if i parse JSON as object.
$.ajax({
url: 'queries.php?q=count',
type: 'post',
//data: data,
datatype: 'json',
success: function(data) {
//var dataobject = jQuery.parseJSON(data);
//console.log(dataobject);
//var var2 = dataobject[0].number; ---->THIS WORKS!
//alert(JSON.parse(data).length); ---->THIS WORKS!
//console.log(data.length); ---->Undefined
console.log(typeof data); ---->string
console.log(data[0]["number"]);---->Undefined,i want this to work!!!
}
});
Thw SQL i use in php is :
switch ($_GET["q"]) {
case "count":
$sql = "SELECT count(*) as number from
(SELECT Employees.emp_username, .............
where Employees.emp_username = ? and Year(emp)=2016 and Month(emp)= MONTH(getdate()) ) as rows1 ";
$stmt = sqlsrv_prepare( $conn, $sql , array(&$_SESSION["username"] ));
break;
default: header("Location: index.php"); }
if( !$stmt ) { die( print_r( sqlsrv_errors(), true)); }
sqlsrv_execute($stmt);
$rows = array();
if(sqlsrv_execute($stmt)){
while($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)){
$rows[] = $row; }
} else{
die( print_r( sqlsrv_errors(), true));
}
print json_encode($rows);
Your variable type is string. You must parse it first.
$.ajax({
url: 'queries.php?q=count',
type: 'post',
//data: data,
datatype: 'json',
success: function(data) {
//var dataobject = jQuery.parseJSON(data);
//console.log(dataobject);
//var var2 = dataobject[0].number; ---->THIS WORKS!
//alert(JSON.parse(data).length); ---->THIS WORKS!
//console.log(data.length); ---->Undefined
console.log(typeof data); ---->string
data = JSON.parse(data);
console.log(data[0]["number"]);---->Undefined,i want this to work!!!
}
});
You have to parse the data first, like you did with jQuery.parseJSON(data)
or like in the alert JSON.parse(data)
.
data
is a string object, so when you access the element [0]
you are getting the first character of the string. In your example: [
. This is the first element of the string [{"number":2}]
.
My suggestion is to apply [0]['number'] to dataobject
, so your code should look like this:
$.ajax({
url: 'queries.php?q=count',
type: 'post',
//data: data,
datatype: 'json',
success: function(data) {
var dataobject = jQuery.parseJSON(data);
console.log(dataobject[0]["number"]);
}