Jay Jung
Jay Jung

Reputation: 1895

How do I retrieve lat & long coordinates from the client without them needing to POST once?

I'd like to do some server side processing with their lat/long as soon as they agree to share them--I'd like for the results of that processing to be in the same page the users are in, immediately after they "Allow" location access.

Currently, I am able to retrieve their coordinates, but a POST removed. So when they "Allow", I fill out a hidden lat/long form, and wait for them to POST a form before I do the server side processing with Geodjango.

What's an efficient way to send over the coordinates to the server as soon as they're available, OR retrieve an estimated location, pronto?

Upvotes: 2

Views: 80

Answers (1)

Olivier Pons
Olivier Pons

Reputation: 15778

Yes, you can do this easily:

  • make a view that gets POST parameter as JSON

Python sample:

class MyJsonForAjaxView(generic.View):

    def get(self, request, *args, **kwargs):
        return JsonResponse({'key': value}, safe=False)
  • call that view in JavaScript (= AJAX call) with POST method:

JavaScript code:

$.ajax({
    method: 'post',
    type: 'json',
    cache: false,
    url: 'my_json_url',
    data: {'lat': your_lat, 'lgn': your_lgn}
}).done(function(data) {
    alert('call successfull!!!');
    /* data is filled with Django result, here {'key': value} */
    /* todo: remember the call has been made and it's registered on Django side */
}).fail(function(data) {
    alert('fatal error!');
}).always(function() {
    /* whatever the result, always do something here */
});

You can do this in the background as soon as you have what you need

Upvotes: 2

Related Questions