Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

121
Vistas
Global variable update AJAX POST

Below is my full JS file beginning to end. I set a variable 'rendered' outside all functions. Then, since it is required in the if check just before issuing a POST request I want to use it as flag and update it's value to be true upon post request completion. The issue is that all the console.log calls do print the changed value but it does not persist. When again the position coordinates are fetched automatically in the watchPosition function, calculateDistance function is invoked again. Then, the previous saved value with "window.rendered = true" is not there, it is actually false and it enters the if condition. How can I achieve the goal of not issuing the post request again until another post request changes this flag variable back to false?

var rendered = false;
    
    function myfunc() {
        rendered = true;
        console.log(window.rendered);
    }
    
    function updatePosition() {
        if(navigator.geolocation) {
            navigator.geolocation.watchPosition(calculateDistance);
        }
        else {
            console.log("Geolocation is not supported by this browser.")
        }
    }
    
    function calculateDistance(position) {
        var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
        var target = new google.maps.LatLng(55.85365783555865, -4.288739944549508);
        var dis = google.maps.geometry.spherical.computeDistanceBetween(pos, target);
        console.log(window.rendered);
        var self = this;
        if(dis <= 1000 && dis >= 0 && window.rendered == false) {
            console.log("Distance"+dis);
            var url = '/dogpark/near_park/';
            var csrftoken = getCookie('csrftoken');
            $.ajax({
                url: url,
                type: "POST",
                data: {
                    csrfmiddlewaretoken: csrftoken,
                    in_proximity : 1
                },
                async: false,
                success: function(data) {
                    myfunc();
                    self.rendered = true;
                    window.rendered = true;
                    alert(window.rendered);
                    window.location = '/dogpark/near_park/';
                },
                complete: function(data) {
                    console.log("Trying");
                    window.rendered = true;
                    alert(window.rendered);
                },
                error: function(xhr, errmsg, err) {
                    console.log(xhr.status+": "+xhr.responseText);
                },
                
            });
        }
    
    window.onload = updatePosition()
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

A simple way is to use another variable to track the ajax call completion. So that you don't make another Ajax call until the previous one returns a repsonse(success/failure).

var isWaitingForResponse = false;
...
function calculateDistance(position) {
  ...
  if(dis <= 1000 && dis >= 0 && window.rendered == false && !isWaitingForResponse) {
    isWaitingForResponse = true;
    ...
      success: function(data) {
        isWaitingForResponse = false
        ...
      },
      complete: function(data) {
        isWaitingForResponse = false
        ...
      },
      error: function(xhr, errmsg, err) {
        isWaitingForResponse = false
        ...
      }
...

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda