Callback from $.get is not called and I can’t debug to find out why

Asked

Viewed 196 times

3

I am developing a mobile application (with Cordova) that needs to make a select in online BD, and with this data update the mobile BD, but I came across a problem, I perform select in the mobile BD after performing a

$.get(url, parametro, fuction(data){
});

to select in the online database the registration, and within perform the check if the data are different and if I am doing the update, but when I give a Debug it does not enter into my get I was told that this happens because it’s an ASYNCHRONOUS function but I don’t know how to solve this.

My code:

    queryDB: function (tx) {
        tx.executeSql('SELECT * FROM ouvidoria11', [], app.querySuccess3, app.errorCB);
    },
querySuccess3: function (tx, results) {
        var len = results.rows.length;
        var protocolo;
        var tblText = '';
        if (len < 1) {
            alert("Não existe nenhum cadastro!");
        }
        else {
            for (var i = 0; i < len; i++) {
                if (results.rows.item(i).protocolo == null) {
                    app.protocoloSolicitacao(results.rows.item(i).id, results.rows.item(i).assunto, results.rows.item(i).mensagem, results.rows.item(i).endereco, results.rows.item(i).anexo);
                }
                tblText += '<span onclick="app.guardaVariavel('+results.rows.item(i).protocolo+')"><table id="t01" class="table-bordered">';
                tblText += '<tr><th>Protocolo</th><td>' + results.rows.item(i).protocolo + '</td></tr>';
                tblText += '<tr><th>Assunto</th><td>' + results.rows.item(i).assunto + '</td></tr>';
                tblText += '<tr><th>Mensagem</th><td>' + results.rows.item(i).mensagem + '</td></tr>';
                tblText += '<tr><th>Endereco</th><td>' + results.rows.item(i).endereco + '</td></tr>';
                tblText += '<tr><th>Anexos</th><td>' + results.rows.item(i).anexo + ' </td></tr>';
                tblText += '<tr><th>Prazo</th><td>' + results.rows.item(i).prazo + '</td></tr>';
                tblText += '<tr><th>Status</th><td>' + results.rows.item(i).status + '</td></tr>';
                tblText += '<tr><th>Departamento</th><td>' + results.rows.item(i).nomeDepartamento + '</td></tr>';
                tblText += '</table></span>';
                document.getElementById("tabelaSolicitacao").innerHTML = 

tblText;
                    var protocolo = results.rows.item(i).protocolo;
                    var nomeDepartamento = results.rows.item(i).nomeDepartamento;
                    var prazo = results.rows.item(i).prazo;
                    var statusBD = results.rows.item(i).status;
                    app.atualizarTabela(prazo, statusBD, nomeDepartamento, protocolo);//Chama a função para atualizar os dados
                }
            }
        },
atualizarTabela: function(prazo, statusBD, nomeDepartamento, protocolo){    
        var serviceURL = "http://ouvidoria.azurewebsites.net/Solicitacao/SelectAtualizacao";
        var parametros = { id: protocolo }
        $.get(serviceURL, parametros, function (data) {
            alert("Teste Get");
            if (data[0].meuPrazo != prazo || data[0].status != statusBD || data[0].nomeDepartamento != nomeDepartamento) {
                db.transaction(update, null, null);
                function update(tx) {
                    tx.executeSql('UPDATE ouvidoria11 set prazo = "' + prazo + '", status = "' + statusBD + '", nomeDepartamento = "' + nomeDepartamento + '" WHERE protocolo="' + protocolo + '"');
                }
            }
        });
    },

Obs.: As said it comes to call the function atualizarTabela() but it does not enter the $.get, does not even display the alert('');, he displays the alert() after the end of the for of function querySucess3() then it displays the various times, exactly the number of times the function atualizarTabela() was called in the for of the main function querySucess3()

The meuPrazo is returning of undefined when I set to debug console.log(date) it returns the following:

Object
abort: function ( statusText ) {
always: function () {
complete: function () {
done: function () {
error: function () {
fail: function () {
getAllResponseHeaders: function () {
getResponseHeader: function ( key ) {
overrideMimeType: function ( type ) {
pipe: function ( /* fnDone, fnFail, fnProgress */ ) {
progress: function () {
promise: function ( obj ) {
readyState: 4
responseJSON: Array[1]
responseText: "[{"id":0,"assunto":null,"mensagem":null,"endereco":null,"anexo":null,"status":"Aguardando","meuPrazo":"Indefinido","nomeDepartamento":null,"id_departamento":2}]"
setRequestHeader: function ( name, value ) {
state: function () {
status: 200
statusCode: function ( map ) {
statusText: "OK"
success: function () {
then: function ( /* fnDone, fnFail, fnProgress */ ) {
__proto__: Object
  • When you say "I perform select in the mobile comics then I perform a $.get" you can show the code that does this?

  • You can put the code the same as @Sergio said.

  • Ready made the changes in the post, it was clear this way?

  • You are calling the function atualizarTabela within a for?

  • Why do I check every record with the outside bank

  • I think it’s good to have asynchronous code. I’ll give you an answer here but you can give an example of what results have? (You can do console.log(JSON.stringify(results)); inside querySucess3). And another question: the line document.getElementById("tabelaSolicitacao").innerHTML = tblText; works as you expect?

  • Friend, I had the same problem that you solved creating a variable and each pass I had to do added +1 in the variable, in the end let’s say I had 5 processes, I made an if(variable == 5){} when it will be yes I did the rest when it was not I expected 1s, This I did with javascript and asked again. Really mobile bank is asynchronous.

  • Try to pass the fourth parameter 'JSON'; $.get(url, parametro, fuction(data){&#xA;}, 'JSON');

Show 3 more comments

1 answer

0

Pass the parameter async: false in ajax must solve, I will demonstrate an example:

$.ajax({type:"GET", url:view, dataType:"json", data:data,async:false,              // FAZ UM AJAX SINCRONIZADO COM A FUNCAO
        success: function(json) { retorno = json; },                                    // RETORNO DO AJAX NO SUCCESS
        error: function(json) { retorno=json; },                                        // RETORNO DO AJAX NO ERROR
        beforeSend: function() { $('body').css('cursor','wait'); },                     // RETORNO DO AJAX NO ERROR
        complete: function(){ $('body').css('cursor','default'); }
    }); 

There’s a question like that here https://stackoverflow.com/questions/133310/how-can-i-get-jquery-to-perform-a-synchronous-rather-than-asynchronous-ajax-re

EDIT: in your code up there would look like this to know if any value returned is coming:

$.ajax({type:"GET",url:serviceURL,data:parametros, async:false,
    complete: function (data) {
        console.log(data);
    }
});
  • 1

    The option async: false is in the process of being removed. It will take a long time for the same, but it is preferable to avoid using it. https://xhr.spec.whatwg.org/#Sync-Warning

  • @Oeslei also think that source code should have the logic built in function of running after receiving the get, is the tip

  • Giving an error 'meuPrazo of Undefined'

  • checks if the array is coming with it test a console.log(data) in debug @Viniciusvaz

  • @Sneepsninja I put in the comment the console.log that was returned

  • @Viniciusvaz I edited my answer, take a look there and say what comes from the console.log(data) and not console.log(date[0]. meuPrazo)

  • @Sneepsninja the return is the one I commented, is the return of console.log(data) not the console.log(data[0]. meuPrazo)

  • @Sneepsninja on the line responseText: "[{"id":0,"assunto":null,"mensagem":null,"endereco":null,"anexo":null,"status":"Aguardando","meuPrazo":"Indefinido","nomeDepartamento":null,"id_departamento":2}]" esta retornando mas como faço para exibir este valores?

  • ta seeing that the field meuPrazo is coming undefined, then the problem is there in php, the caompo id_departamento is equal to 2 you could call it thus: data[0]. id_departamento

Show 4 more comments

Browser other questions tagged

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