Reload after update

Asked

Viewed 610 times

4

I am making a status change in my database using $.getJSON, is working, but in return I need to update the div where the data is and I am not able to perform this task, see the code below:

<script>
$(function(){       
    $("[name='btncapa']").on('click',function(e){

        var IdProduto   = $(this).attr('IdProduto');
        var IdProdutoFoto = $(this).attr('IdProdutoFoto');
        var $el = $(this);

        bootbox.dialog({
            message: "Confirma a marcação de capa?",
            title: "Capa",
            buttons: {
                success: {
                    label: "Sim",
                    className: "btn-success",
                    callback: function() {
                        $.getJSON('MarcaItemFoto.php', {IdProduto: IdProduto, IdProdutoFoto: IdProdutoFoto},  function(resposta){
                            $("#diverro").html("<div class='alert alert-error'><button type='button' class='close' data-dismiss='alert'>&times;</button><strong>ERRO!</strong> " + resposta.erro + "</div>");
                        });
                        $el.parents('li').load();
                    }
                },
                danger: {
                    label: "Não",
                    className: "btn-danger",
                    callback: function() {
                    }
                }
            }
        });
        e.preventDefault();
    });
});
</script>
  • .load(URL) has a mandatory parameter, a URL that will return this list li, $.getJSON(URL, json, functionSucess) from what I understand, you want to upload the list li after doing 'Marcaitemfoto.php'? 'Marcaitemfoto.php' returns what?

  • Hello bigown, good night, it returns me the status of the operation, being true/false ai handle the message if it is an error, otherwise I would like to update the list.

3 answers

4


There are two potential problems with your code:

  1. You seem to be dealing only with error conditions in callback (anonymous function you pass as pro parameter getJSON), but not conditions of success. Also, as mentioned by @marcusagm, this function will only be called if the request succeed, although the logic of your program no. If there is a problem with the request itself (ex.: timeout, 404 not found, 500 internal server error, etc) no code will be called.

    To correct this, I suggest also pass a callback for errors. If you are using a recent version of jQuery, ideally:

    $.getJSON(url, parametros)
        .done(function(resposta) { /* sucesso */ })
        .fail(function() { /* erro */ });
    

    If you really want a single function to treat error or success, you can use the then:

    $.getJSON(url, parametros).then(function(resposta) { 
        /* sucesso ou erro */ 
    });
    
  2. Ajax requests, as the name says, are asynchronous. The call of getJSON returns even before it has been performed (and completed). Therefore, any code you put after it will execute before of Ajax being done, no afterward.

    Anything you want to run only after the answer is ready, you should put in the callback of the request. Example:

    $.getJSON(url, parametros).done(function(resposta) { 
        $el.parents('li').load();
    });
    

    (I don’t know if this was your goal with this line of code, but I suspect it is: reload only after Ajax is ready)

P.S. In the question you also say you are making a "status change", right? In that case, the best practice would be not to use a HTTP GET for this, but rather a POST. Example:

$.post(url, parametros, "json").done(function(resposta) { 
    $el.parents('li').load();
});
  • 1

    Remember that the load function does not load the data directly. It is necessary to handle the update for each part, either by returning the html list on the return of the request and updating using the html() function. Or return a JSON and treat right away by adding html

2

You are making the request and in case of success treated only for error.

$.getJSON('MarcaItemFoto.php', {IdProduto: IdProduto, IdProdutoFoto: IdProdutoFoto},  function(resposta){
  // Aqui você deve tratar se realmente ocorreu um erro ou não.
  // Esta funcão é utilizada caso a requisição retorne um status de sucesso.
  // Aqui você tambem deve tratar os casos de sucesso, como atualizar a lista de que precisa.
});

Load makes another Ajax request see the parameters on documentation

$el.parents('li').load('caminho/para/retornar/o/html/atualizado');

I recommend to treat also when the request returns an unexpected error code using jquery’s fail() function. It would look like this:

$.getJSON('MarcaItemFoto.php', {IdProduto: IdProduto, IdProdutoFoto: IdProdutoFoto},  function(resposta){
   // Ação após obter resultado com código de sucesso
}).fail(
  function () {
    // Ação após obter resultado com código de erro
  }
);

-1

The solution to my problem was this:

$.post(url, parametros, "json").done(function(resposta) { 
    $el.parents('li').load();
});

Tip given by mgibsonbr. Thank you.

Browser other questions tagged

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