Reload after update

4

I am making a status change in my database using $.getJSON , it works, 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: / p>

<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>
    
asked by anonymous 03.02.2014 / 19:02

3 answers

4

There are two potential issues with your code:

  • You seem to be only dealing with error conditions in the callback (anonymous function that you pass as pro getJSON parameter), but not success conditions. Also, as mentioned by @marcusagm, this function will only be called if the request succeeds, even though your program logic does not. If there is a problem with the request itself (eg , 404 not found, 500 internal server error, etc.), no code will be called.

    To fix this, I suggest passing a callback for errors as well. If you are using a recent version of jQuery, the ideal would be:

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

    If you want a single function to handle error or success, you can use then :

    $.getJSON(url, parametros).then(function(resposta) { 
        /* sucesso ou erro */ 
    });
    
  • Ajax requests, as the name implies, are asynchronous . The call of getJSON returns before it has even been completed (and completed). So any code that you put after it will run before Ajax is done, not after .

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

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

    (I do not 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 that you are doing a "status change", right? In this case, the best practice would be not to use HTTP GET for this, but a POST . Example:

    $.post(url, parametros, "json").done(function(resposta) { 
        $el.parents('li').load();
    });
    
        
    03.02.2014 / 19:34
    2

    You are making the request and in case of success it is 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 request Ajax see the parameters in documentation

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

    I recommend that you also treat when the request returns an unexpected error code using the jquery 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
      }
    );
    
        
    03.02.2014 / 19:19
    -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.

        
    13.02.2014 / 13:37