I'm having some trouble getting a JSON request to work properly. I'm trying to send some data from PHP to JS via a JSON object, but I'm not having any luck. The PHP code that does the transfer is as follows:
Code:
$output = array();
$string = $forecast->date->weekday . "<br /> <img src=" . $forecast->icon_url .
" /> <br /> " . $forecast->high->fahrenheit . " " . $forecast->low->fahrenheit . "<br />" . $forecast->conditions . "<br />" ;
$output["day1"] = $string;
echo json_encode($output);
All the variables listed are text/number values pulled from a JSON object (I have tested, and the code was read IN properly, so that's not the issue). I know this may not be the best way to do this, but for now I'm just trying to figure out how to get the transfer to work properly. The JavaScript that is interpreting it is below.
Code:
req.open("GET","GetForecast.php",false);
req.setRequestHeader("Content-Type", "text/plain; charset=UTF-8");
var data = $.parseJSON( "(" + req.responseText + ")" );
This code crashes when it gets to the parseJSON function, probably because it's receiving some mangled nastiness as input. When I print out req.responseText, I get the following:
Code:
{"day1":"Wednesday<br \=""> <img src="http:%5C/%5C/icons-ak.wxug.com%5C/i%5C/c%5C/k%5C/tstorms.gif" \=""> <br \=""> 88 57<br \="">Thunderstorm<br \="">","day2":""}
NOTE: the variables used above are, in order, "Wednesday", "http://icons-ak.wxug.com/i/c/k/tstorms.gif", "88", "57", and "Thunderstorm"
Not sure what I'm doing wrong here, but any help would be appreciated. Thanks.
EDIT: I decided this was a pointless way to go about this, so instead I am sending raw JSON to be formatted client-side. However, the interpretation is still failing at the same line as before. I receive properly formatted data this time, as shown below, but the JSON interpreter fails every time. Any suggestions?
Code:
[{"weekday":"Wednesday","icon":"http:\/\/icons-ak.wxug.com\/i\/c\/k\/tstorms.gif","high":"88","low":"57","state":"Thunderstorm"}]
Addition info: I am getting "SyntaxError: JSON.parse: unexpected character" now that I wised up and used some error checking (kinda stupid not to have tried it before, but oh well). However, according to
http://jsonlint.com/ my JSON is perfectly valid.