0

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.

3 Answers 3

2

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');
   });
Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

0

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.

1 Comment

it's not that it may be string...it will always be string

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.