I need to make a get request to google places api however I can't use just javascript because it does not support jsonp. I read that I could do a get request using a php file and then do a normal jquery ajax call to that in order to get the json data. However I created the php file using
<?php
echo file_get_contents("https://maps.google...");
?>
and then using a jquery ajax request to this file hosted on my http:localhost/ server on my ubuntu distro, yet i am getting a 500 http server error. What am I doing wrong or how do I go about doing this correctly?
</script>
<script>
$(document).ready(function(){
$.ajax({
url: 'http://localhost/places.php',
dataType: "json",
type: "GET",
success: function( data){
document.getElementById("paragraph").innerHTML= data.result[0].name;
},
error: function(request, status, error){
document.getElementById("paragraph").innerHTML= "error";
}
})
});
</script>
<body>
<p id="paragraph">
Untouched Text.
</p>
<button id="b1">Click Me!</button>
</body>
The only error message I get using firebug is 500 Internal Server Error so I don't think its my html, javascript, or jquery.
You are calling Google API and must return a JSON, so this ought to be enough:
<?php
$json = file_get_contents("http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true_or_false");
$data = json_decode($json);
// manipulate data and rebuild json with $json = json_encode($data) if needed
Header("Content-Type: application/json");
die($json);
?>
This works, in that Google answers me with a correctly formed, if succinct, JSON:
{
"results": [ ],
"status": "REQUEST_DENIED"
}
With proper API Key configuration you ought to get this working. Check that the call is working in your browser (without cookies, etc. - a clean session, which is what file_get_contents()
is going to give you) and that your PHP installation is capable of recovering SSL data (it should, but let's check), ie,
file_get_contents("https://www.google.com/");
ought to recover Google's home page.
This call needs no authentication (there's a rate limit, but I think it's unlikely you'll be making all the calls required to get you shut out):
http://maps.googleapis.com/maps/api/directions/json?origin=Toronto&destination=Montreal&sensor=false
The above will return a very complex JSON with possibly accented characters in. Now that I come to think of it, the Header
above would be better like this:
Header('Content-Type: application/json;charset=UTF-8');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.