Algernop K. Algernop K. - 6 months ago 11
Ajax Question

Failing to return what I want via ajax (Google Geocoding)

I have 5 input fields, one for each day of the week. They're saved on

keyup
into a variable, which is working according to
console.log
.

<script>
$(document).ready(function(){
console.log("Ready!");
$("input[type='text']").keyup(function() {
console.log("Something changed");

var mon = $("#mon").val();
var tue = $("#tue").val();
var wed = $("#wed").val();
var thu = $("#thu").val();
var fri = $("#fri").val();

console.log("Monday means:" + mon);

$.ajax({
type: "post",
url: "map.php",
data: 'mon=' + mon + '&tue=' + tue + '&wed=' + wed + '&thu=' + thu + '&fri=' + fri,
dataType: 'json',
success: function(data){
console.log("Your data is:" + data);
},
});
});
});
</script>


However, I am failing to return either an "Not working" or what I'm actually after. Shouldn't "Not working" be returned if the API call within the php file failed?

// This is not returning anything
if($_POST['mon']) {
$mon = $_POST['mon'];

// Working fine manually entered into the web browser
$urlMon = "https://maps.googleapis.com/maps/api/geocode/json?address=".$mon."&key=myKey123";
$jsonMon = json_decode(file_get_contents($urlMon), true);
$address = $jsonMon['results']['formatted_address'];

if(isset($address)) {
echo json_encode($address);
} else {
echo json_encode("Not working");
}
}


I know that the ajax itself is working, because this is working:

// This returns the variable I sent according to the console log.
if($_POST['mon']) {
$mon = $_POST['mon'];
echo json_encode($mon);
}


I'm quite new at this, I'm sure I've missed something obvious/done something really wrong.

Thanks in advance

Answer

The reason why you weren't seeing anything from your console.log() call is because you were explicitly telling jQuery to expect a json result. And, even though you were calling json_encode() on your error text, it it was still really just plain text that jQuery wasn't interpreting as json. Since you told it to expect json and it wasn't getting it, the success callback wasn't happening. Remove dataType: 'json', unless you a.) know that you will always get a json response or b.) have an error callback as well.

The reason why we were hitting your error condition is because $jsonMon['results']['formatted_address'] should have been $jsonMon['results'][0]['formatted_address']. You also need to urlencode the address that you are sending to the maps API.

Comments