I'm trying to POST
to a PHP controller using jQuery Ajax. I then want my controller to retrieve data from an API and return the data to my AJAX function.
Here is my javascript:
$(function() {
$.ajax({
type: 'POST',
url: '/mycontroller/myaction/',
success: function(data) {
console.log(data);
}
});
});
Here is my action in my controller:
public function myaction() {
$ch = curl_init();
$endPoint = 'https://endpointfortheapi.com';
curl_setopt($ch, CURLOPT_URL, $endPoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json; charset=utf-8'
));
$response = curl_exec($ch);
$response = json_encode($response);
echo $response;
curl_close($ch);
}
This seems to work, however, when I use json_encode()
the array is returned as an escaped string, not a json object. When I console.log(data)
in my AJAX request, I see a string like this:
"[{\"firstProperty\":\"firstValue\",\"secondProperty\":\"secondValue\"}]"
How can I encode the response array to be an actual JSON object?