Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

javascript help: i have a php page that echos

['A', 28.006660938911], ['B', 71.993339061089]

now i need this converted into an array in javascript, but in ajax, "var myData = new Array($http.responseText);" does not work

share|improve this question
JSON is your friend: how can json_encode be used here? (Make sure to use the correct flags! :-) Also, this has been asked on SO like a bazillion times... on the JavaScript side use the appropriate JSON decoding, of course. There is no such Array constructor that takes a string. It just doesn't work like that. – user166390 Oct 25 '11 at 5:37
I second what Pst said. JSON will undoubtedly be the easiest (and probably most efficient) way to accomplish this. – Josh1billion Oct 25 '11 at 5:43
up vote 3 down vote accepted

If given string is:

var s = "['A', 28.006660938911], ['B', 71.993339061089]";
  1. try evaluating it (if you have no access to the PHP code you are using):

    var array = eval("[" + s + "]");
    
  2. try changing the response to JSON format (if you HAVE access to that PHP code):

    echo json_encode(array(array('A', 28.006660938911), array('B', 71.993339061089)));
    
  3. if i am wrong and you are given with two different arrays, try splitting the string first

share|improve this answer
Awesome eval worked! thanks! – James Gu Oct 25 '11 at 23:00
var myJSONObject = <?php echo json_encode($someArray); ?>
alert(  myJSONObject.keyInTheArray  )
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.