Reza Asgharzadeh
Reza Asgharzadeh

Reputation: 141

sending an array to javascript through ajax

I am trying to send an array from PHP to Ajax in javascript. my array in PHP file "myphp.php" is $parts and is multidimentional.

I have used both echo $parts and echo json_encode($parts) none works for me. $parts has 2 rows and 2 columns this is the result of var_dump:

array(4) { [0]=> array(3) { [0]=> string(13) "1350655763.12" [1]=> string(2) "25" [2]=> string(1) " " } [1]=> array(3) { [0]=> string(13) "1350655763.12" [1]=> string(2) "26" [2]=> string(0) "" } [2]=> array(1) { [0]=> string(0) "" } [3]=> array(1) { [0]=> string(0) "" } }

I want to send the hole array to Ajax but just display $parts[0][0] on the web page. When I use

echo $parts 

in myphp.php file: "Array" name is displayed on the web page When I use

echo json_encode($parts) 

in myphp.php file: all components of the array are displayed instead of the first one

        <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <script>
function getXMLHttp()
{
  var xmlHttp

  try
  {
    //Firefox, Opera 8.0+, Safari
    xmlHttp = new XMLHttpRequest();
  }
  catch(e)
  {
    //Internet Explorer
    try
    {
      xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch(e)
    {
      try
      {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
      }
      catch(e)
      {
        alert("Your browser does not support AJAX!")
        return false;
      }
    }
  }
  return xmlHttp;
}

function MakeRequest()
{
  var xmlHttp = getXMLHttp();

  xmlHttp.onreadystatechange = function()
  {
    if(xmlHttp.readyState == 4) 
     { 
      var parts=JSON.parse(xmlHttp.responseText); 
      document.getElementById('ResponseDiv').innerHTML = parts[0][0]; 
     }
  }

  xmlHttp.open("GET", "myphp.php", true); 
  xmlHttp.send(null);
}


result=MakeRequest();



</script>


  </head>
  <body>

    <div id='ResponseDiv'>
      This is a div to hold the response.
    </div>
  </body>
</html>

How should I change these codes to just get parst[0][0] on the webpage? Thanks in advance for you help

Upvotes: 1

Views: 654

Answers (2)

kwelsan
kwelsan

Reputation: 1219

You should parse your json encoded data into javascript before use it. Please check json here

http://www.json.org/js.html

Please try this code:

result = MakeRequest();
var myObject = eval('(' + result + ')');
alert(myObject[0][0]);

Upvotes: 0

Dhairya Vora
Dhairya Vora

Reputation: 1281

you need to use JSON.parse on at javascript and json_encode at php.

PHP:

$parts = array();
....
echo (json_encode($parts));

Javascript:

var parts = JSON.parse(xmlHttp.responseText);

Optionally, on your PHP page, you can also define header('Content-type: application/json');

Upvotes: 1

Related Questions