Change variable value in Ajax

Asked

Viewed 1,231 times

2

The Problem

I have the variable flagExistenciaArquivo, and I need it updated if the file exists or not. I call the function verificaExistenciaArquivo within another function, setting as parameter a briefcase of that file and file name. If the file is found, it returns true, otherwise, false. I need you to go into success or error from Ajax, I can change the value of the flag variable.

My Code

var flagExistenciaArquivo = true;

function verificaExistenciaArquivo(pasta, nomeArquivo) {
    var baseUrl = 'http://' + $(location).attr('hostname') + '/monitoramento-mobile/assets/fotos/';

    if(pasta == 'assinaturas_entrevista') {
        arquivo = baseUrl + 'assinaturas_entrevista/' + nomeArquivo;
    }else if (pasta == null) {
        arquivo = baseUrl + nomeArquivo;
    }

    $.ajax({
        url: arquivo,
        type:'HEAD',
        success: function()
        {
            //mudar valor da variável para true
        },
        error: function()
        {
            //mudar valor da variável para false
        }
    });
}
  • Don’t just use it flagExistenciaArquivo = true; or flagExistenciaArquivo = false; ?

  • 1

    In fact, the successful request will always fall into the success, then you have to check there by taking the callback return parameter, e.g. success(data), whereas data must be your boolean return.

  • 1

    @Dontvotemedown You’d have an example code so I’d better understand what the callback would look like ?

  • The @Diegosouza explained well.

2 answers

4


as the AJAX method is asymchronous, the function return verificaExistenciaArquivo will occur before the return of AJAX.

You can even set the property async: false of $.ajax, but this is not recommended, the ideal is to pass a function of callback for verificaExistenciaArquivo.

function verificaExistenciaArquivo(pasta, nomeArquivo, callback) {
    var baseUrl = 'http://' + $(location).attr('hostname') + '/monitoramento-mobile/assets/fotos/';

    if(pasta == 'assinaturas_entrevista') {
        arquivo = baseUrl + 'assinaturas_entrevista/' + nomeArquivo;
    }else if (pasta == null) {
        arquivo = baseUrl + nomeArquivo;
    }

    $.ajax({
        url: arquivo,
        type:'HEAD',
        success: function()
        {
            callback(true);
        },
        error: function()
        {
            callback(false);
        }
    });
}

verificaExistenciaArquivo("nomeDaPasta", "nomeDoArquivo", function (existe) {
    console.log(existe ? "Arquivo Existe" : "Arquivo não existe");
});

In this case it is also not interesting to have a global variable to inform the existence of the file, either you delete it as in the example above, or declare it within a closure.

A second problem is that you are downloading the entire file just to know if it exists, the ideal would be to abort the request as soon as the server responds with the readyState: 2 (request recebido)

var uploadFile = document.getElementById("uploadFile");
var linkURL = document.getElementById("linkURL");

var createLink = document.getElementById("createLink");
var destroyLink = document.getElementById("destroyLink");
var linkExists = document.getElementById("linkExists");

// criar um link em memoria para o arquivo selecionado.
createLink.addEventListener("click", function (event) {
  if (uploadFile.files.length > 0) {
    linkURL.value = URL.createObjectURL(uploadFile.files[0]);
  }
});

// destruir o link em memoria para o arquivo selecionado
destroyLink.addEventListener("click", function (event) {
  if (linkURL.value) {
    URL.revokeObjectURL(linkURL.value);
  }
});

// verificar se o link em memoria existe
linkExists.addEventListener("click", function (event) {
  if (linkURL.value) {
    verificaExistenciaArquivo(linkURL.value, function (exists) {
      // exists pode assumir 3 valores:
      // true: arquivo encontrado
      // false: arquivo não encontrado
      // undefined: erro na requisição
      console.log(exists);
    });
  }
});

// verificar se existe algum arquivo no link em memoria.
var verificaExistenciaArquivo = function (url, callback) {
  var done = false;
  var xmlHttp = new XMLHttpRequest ();  
  xmlHttp.onreadystatechange = function () {
    //readyState 0 a 4: 
    //0: request não enviado
    //1: conexão estabelecida
    //2: request recebido
    //3: processando request
    //4: resposta pronta     
    var response = { readyState: xmlHttp.readyState, status: xmlHttp.status };
    if (!done) {     
      switch (response.readyState)
      {
        // 0 antes do 2 - caso o request seja abortado antes da resposta do servidor (timeout).
        case 0: 
          callback(undefined); 
          break;
        //conexão com o servidor bem sucessida, e o mesmo já respondeu com um status.
        case 2:
          done = true;
          xmlHttp.abort();
          switch (response.status)
          {
            case 200: callback(true); break;
            case 404: callback(false); break;
            default: callback(undefined); break;
          }
          break;
        // 4 antes do 1 - Conexão recusada (possivelmente CORS bloqueado)
        case 4: 
          callback(undefined); 
          break;
      }
    }    
  }

  xmlHttp.open("GET", url);
  xmlHttp.send();
}
#linkURL {
    width: 500px;
}
<div>
    <input id="uploadFile" type="file" />
<div>
    <input id="createLink" type="button" value="Criar Link" />
    <input id="destroyLink" type="button" value="Destruir Link" />
</div>
<div>
    <label>
        Link Criado:
        <input id="linkURL" type="text" disabled />
    </label>
</div>
<div>
    <input id="linkExists" type="button" value="Verificar Link" />
</div>

  • It will only fall into the error callback if there is error in the request, otherwise it will fall into the Success with the return in the first parameter.

  • Thank you so much @Toby

  • @Dontvotemedown, Don’t Vote Me Down

  • From what I understand he is asking a file to the server and not accessing an API to ask if a particular file exists or not, so if the file exists it will return a code 200 (sucess), if there is no code 404 (error)of course other error situations can create a false positive.

  • So it shows on the error line: "callback is not definied".

  • note that I added one more argument to the function verificaExistenciaArquivo, in case the callback

  • Oh yes, true, I hadn’t changed the url. I put it above if the = null file, but apparently it’s always falling into Success. And the.log console is not showing, although Chrome does not indicate a JS error.

  • I’ll put an example using Xmlhttprequest.

  • @Allanramos, take a look now.

Show 4 more comments

2

It was easier for you to check the existence of the file on a server-side page. Probably PHP you are using.

PHP

<?php
    $file = $_POST['file'];
    $caminho = 'dir/';
    if(file_exists($caminho.$file))
       $boo = "true";
    else
       $boo = "false";

    return $boo;
?>

And in JS you get the return of the PHP page and just treats in callback of function success.

JS

var flagExistenciaArquivo = true;

function verificaExistenciaArquivo(pasta, nomeArquivo) {
    $.ajax({
        url: 'pagina.php',
        data: { file: nomeArquivo },
        type:'POST',
        async: false,
        success: function(result){
            if(!result)
               flagExistenciaArquivo = false;
        },
    });
    return flagExistenciaArquivo;
}
  • Blz, I agree, but as @Dontvotemedown said, I would have to make a callback to change the state of that variable, correct ?

  • Exactly. I edited my post.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.