I have created a script that takes 2 post codes and returns the distance, if the distance is less than 4 miles it returns a success message, if it is over 4 miles it returns another message. It should also throw an error if the form field is empty.
I'd love to be able to return the data without refreshing the page but so far i can't seem to get the ajax request working, it just doesn't do a anything at all.
jQuery isn't my fortè i pieced this together by searching online.
$(document).ready(function () {
$('#postcode-form').submit(function (event) {
event.preventDefault();
$('.help-block').remove(); // remove the error text
var formData = {
'destination': $('input#destination').val()
};
$.ajax({
type: 'POST',
url: 'includes/postcode-finder.php',
data: formData,
dataType: 'json',
encode: true
}).done(function (data) {
if (!data.success) {
if (data.errors.destination) {
$('#destination-group').append('<div class="help-block">' + data.errors.destination + '</div>');
}
} else {
$('#postcode-form').append('<div class="alert alert-success">' + data.message + '</div>');
}
})
});
});
and the php code:
$bakery = 'DH12XL'; $destination = $_POST['destination'];
$errors = [];
$result = [];
if(empty($destination))
{
$errors['postcode'] = 'Postcode is required';
}
if(!empty($errors))
{
$data['success'] = false;
$data['errors'] = $errors;
}
else
{
$url = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=$bakery&destinations=$destination&mode=bicycling&language=en-EN&sensor=false&units=imperial";
$google = @file_get_contents($url);
$result = json_decode($google, true);
$distance = $result['rows'][0]['elements'][0]['distance']['text'];
$many_miles = str_replace(' mi', '', $distance);
if($many_miles > 4.0)
{
$data['message'] = 'Collection only for this postcode';
}
else
{
$data['message'] = 'Good news, we deliver!';
}
$data['success'] = true;
echo json_encode($data);
}