Goodbytes
Goodbytes

Reputation: 694

AJAX request fails to work

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);
}

Upvotes: 0

Views: 71

Answers (1)

bcmcfc
bcmcfc

Reputation: 26755

You're using jQuery 1.4.4, which doesn't return Promises from $.ajax and therefore the .done() function isn't available.

You have two options:

Update jQuery (ensure you test anything else that's leaning on it if you do, though!)

Or use the success parameter instead:

$.ajax({
    type: 'POST',
    url: 'includes/postcode-finder.php',
    data: formData,
    dataType: 'json',
    encode: true,
    success: function (data) {
        // do stuff
    }
});

From the docs:

The jqXHR objects returned by $.ajax() as of jQuery 1.5 implement the Promise interface, giving them all the properties, methods, and behavior of a Promise (see Deferred object for more information).

Upvotes: 2

Related Questions