[Answered ]-How to send latitude and longitude to django server using AJAX

2👍

You’re right, it’s an ajax/async issue. Everything that uses the result of getCurrentPosition should be either in that callback function, or split out into a new function that gets called by the callback. Your reusable functions can be moved outside so they are globally scoped in case you need to use them again. For example:

{% block js %}
    <script>
      function csrfSafeMethod(method) {
        // these HTTP methods do not require CSRF protection
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
      }

      $.ajaxSetup({
        beforeSend: function(xhr, settings) {
          if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
          }
        }
      });

      if ("geolocation" in navigator) {
        navigator.geolocation.getCurrentPosition(
          function (position) {
            console.log('Position has been set successfully');

            dataToSend = {
              "fbpost": $("input[name=fb-post]").is(':checked'),
              "latitude": position.coords.latitude,
              "longitude": position.coords.longitude
            };

            $.ajax({
              type: "POST",
              dataType: 'json',
              url: {% url 'pledges:home' %},
              data: JSON.stringify(dataToSend),
              success: function (msg) {
                console.log('Succeeded!');            
              },
              error: function (err) {
                console.log('Error!');
              }
            });
          }, function (error) {
              console.log('Position could not be obtained.')
          }
        );
      }
  </script>
{% endblock %}
👤James

Leave a comment