Simon
Simon

Reputation: 147

Passing variables in jQuery

I am using geocomplete lib to fetch the lat and lng of an address provided in an input field. I then need to pass the lat and lng onto a from to submit the data. However every time I do I get the following error 'Uncaught ReferenceError: lat is not defined'

var option = {
    types: ['(cities)'],
    country: 'GB'
};
$("#location").geocomplete(option).bind("geocode:result", function(event,
    result) {
    console.log(result.geometry.location.lat());
    console.log(result.geometry.location.lng());
    var lat = result.geometry.location.lat()
    var lng = result.geometry.location.lng()
});
$(document).ready(function() {
    $('form.ajax').on('submit', function(e) {
        e.preventDefault();  
        var params = {
            lat: lat,
            lng: lng,
        }
        $.ajax({
            type: 'POST',
            data: params,
            url: 'save_to_json.php',
            success: function(data) {
                console.log('success');
                console.log(data);
            },
            error: function(data) {
                console.log('error');
                console.log(data);
            },
            complete: function() {
                console.log('complete');
            }
        });
        return false;
    });
});

Upvotes: 3

Views: 105

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337691

You need to define the lat and lng variables in a higher scope so that both the geocode:result handler and the form submit handler can access them. Try this:

vat lat, lng;

$("#location").geocomplete(option).bind("geocode:result", function(event, result) {
    // note the removal of 'var'
    lat = result.geometry.location.lat()
    lng = result.geometry.location.lng()
});

Alternatively if you'd prefer to avoid global variables, you could set those values as data attributes on the form to be read at the point of submission:

$("#location").geocomplete(option).bind("geocode:result", function(event, result) {
    $('form.ajax').data({
        lat: result.geometry.location.lat()
        lng: result.geometry.location.lng()
    });
});

$(document).ready(function() {
    $('form.ajax').on('submit', function(e) {
        e.preventDefault();  
        var $form = $(this);
        var params = {
            lat: $form.data('lat'),
            lng: $form.data('lng'),
        };
        // the rest of your AJX code...
    });
});

Upvotes: 3

Related Questions