1

I'm trying to use the ajax response as an argument for the function drawing the chart with google charts.

This is the JS code:

data.addRows([['One', 5], ['Two', 2]]);

As you can see, the argument contains a couple of square brackets with the "chart's unit" name and its value. Everything works. However when I pass ajax responseText as the argument, it doesn't work at all.

data.addRows(xmlhttp.responseText);

The PHP code returns json_encode($value), where the $value variable is this string: [[one, 5], [two, 2]]

So as the result I get:

"[['one', 5], ['two', 2]]"

BTW. I also tried removing double quotes from the string in the JS code - still no results.

What's wrong? The firebug gives me some strange errors: Argument given to addRows must be either a number or an array...

How should I fix this?

user1615069
  • 581
  • 3
  • 13
  • 25
  • what do you get if you console.log(xmlhttp.repsonseText); ? – Aydin Hassan Oct 20 '12 at 13:43
  • It seems the result needs to be transformed into an object first. I would look for a JSON parser to convert the result before feeding into the `addRows()` function. – inhan Oct 20 '12 at 13:46
  • I've used json_encode(), shouldn't this be enough? Alerting response gives me the proper string, the same string works when I use it as an argument. – user1615069 Oct 20 '12 at 13:51
  • console.log? It just gives me an error...somewhere in the google code: "if (!utl.isIE()) {" here. – user1615069 Oct 20 '12 at 13:52
  • 2
    Well as said above it is probably because it is just a string to javaScript. Try using data.addRows(JSON.parse(xmlhttp.repsonseText)); – Aydin Hassan Oct 20 '12 at 13:54
  • Well, it gives me "JSON.parse: unexpected character", both with json_encode() and without it. – user1615069 Oct 20 '12 at 14:07

2 Answers2

3

data.addRows is expecting a real JavaScript array, and you're passing it a string. In order to convert the string to an array, you should use a JSON parser. However, the response you're getting from your server is not valid JSON due to the single quotes.

Steps:

  1. Update your server to send a valid JSON response which includes sending the correct mime type application/json. Following standards is helpful if you use an ajax library like jQuery which can do the JSON parsing for you.

  2. Parse the responseText yourself using something like JSON.parse(...) or use an ajax library like jQuery to do it for you. Either way, you need to convert the responseText string to a real JavaScript array.

Community
  • 1
  • 1
Mike Valenty
  • 8,525
  • 2
  • 27
  • 32
1

You should be able to do data.addRows(JSON.parse(xmlhttp.responseText));. However, the single quotes are going to give you problems and so you need to somehow tell PHP to use double quotes for the keys.

You could do something like data.addRows(JSON.parse(xmlhttp.responseText.replace(/'/, "\"")));`, but it would be far better to make sure that PHP uses the right quotes.

Vivin Paliath
  • 87,975
  • 37
  • 202
  • 284