Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
    });
});
like image 356
Simon Avatar asked Feb 03 '26 21:02

Simon


1 Answers

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...
    });
});
like image 148
Rory McCrossan Avatar answered Feb 06 '26 11:02

Rory McCrossan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!