Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

120
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda