I'm having a bit of a problem reading JSON data that I generate in PHP and then pass back to my Javascript and I'm not sure why.
Here is the PHP:
header("content-type: text/json");
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
//execute post
$result = curl_exec($ch);
// echo the result as a JSON object
echo json_encode($result);
And here is the Javscript:
$.post("payment_do.php", { "token": response.response.token, "ip_address": response.ip_address}).done(function(data) {
console.log(data);
});
It seems as though if I take the header line away in the PHP I get a response that I can read in the Javascript but I cannot access any of the elements the way you would expect. If I leave the header in there, I get no response readable by the javascript.
EDIT: Now getting a response from the php, looks like this:
"{\"response\":{\"token\":\"ch_9knTXHoU0dVZsl7iMHyHGg\",\"success\":true,\"amount\":9900,\"currency\":\"AUD\",\"description\":\"test\",\"email\":\"[email protected]\",\"ip_address\":\"1.1.1.1\",\"created_at\":\"2013-03-18T23:49:12Z\",\"status_message\":\"Success!\",\"error_message\":null,\"card\":{\"token\":\"test_token\",\"display_number\":\"XXXX-XXXX-XXXX-0000\",\"scheme\":\"master\",\"address_line1\":\"123 Fake Street Fakington\",\"address_line2\":null,\"address_city\":\"moon\",\"address_postcode\":\"2121\",\"address_state\":\"NSW\",\"address_country\":\"Australia\"},\"transfer\":[],\"amount_refunded\":0,\"total_fees\":999,\"merchant_entitlement\":999,\"refund_pending\":false}}"
In the end I had to remove the json_encode function in the php and just return the result. In the javascript (using jQuery) I then called:
data = $.parseJSON(data);
With which I could then access the elements of the object.