Reputation: 241
The problem I am facing is this that when I pass an array from a PHP file to another file javascript using Ajax I get correct input but the length of the array is wrong. I don’t know what I am doing wrong. These are my two files some code.
Firstfile.php:
function check()
{
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState==4 && xmlhttp.status==200)
{
graphData=xmlhttp.responseText;
alert(graphData);
// getting alert [["01_Mar_2016",38430],["02_Mar_2016",97183],["03_Mar_2016",107122]]
alert(graphData.length);
//getting alert 68 but it should be 3
}
else if(xmlhttp.status==404)
{
graphData="File not found";
}
}
xmlhttp.open("GET","SeocndFile.php",true);
xmlhttp.send();
}
SeocndFile.php
while($result = mysql_fetch_assoc($qryResult))
{
$data[] = array((string)$result['mimiDate'], (int)$result['sumMimi']);
}
print json_encode($data);
//print like this[["01_Mar_2016",38430],["02_Mar_2016",97183],["03_Mar_2016",107122]]
//which is correct.
Upvotes: 0
Views: 164
Reputation: 10028
As mentioned above check what type of data are you receiving, are in string form.
It is Highly recomended for ajax calls to Use Jquery because you can get the data in a by far more convenient format when responses are json.
An code example using jquery is:
$.get('SeocndFile.php').done(function(data)
{
//do stuff here when sucessfuly retrieve the data
})
.fail(function()
{
//Do stuff when 404 or 500
});
Here it the documentation on how to use it: http://api.jquery.com/jQuery.get/
Also similarry you can use $.post() for HTTP post actions.
Upvotes: 0
Reputation: 171679
responseText
is a string. You need to convert it to array using JSON.parse()
var graphData=JSON.parse(xmlhttp.responseText);
To be safe you should wrap it in a try/catch block or if you are using jQuery then convert to using $.getJSON()
and add error handler
$.getJSON('SeocndFile.php')
.done(graphData){
alert(graphData.length);
})
.fail(function(err){
console.log(err);
alert('Ooops...something went wrong');
});
Upvotes: 2
Reputation: 28538
It is showing length of string as responseText is string so length return number of characters.
You need to parse string to JSON first:
alert(JSON.parse(xmlhttp.responseText).length);
Upvotes: 1