Check return ajax, works only the first time

Asked

Viewed 658 times

1

Good morning friends, I have this code:

$(document).ready(function(){
    $('button').on('click',function(e){
        e.preventDefault();
        var codigo = $(this).attr('id');            
        $.ajax({
            type: 'post', 
            url: '<?= base_url('posts/apaga'); ?>',
            data: 'codigo='+codigo,                
            success: function(msg){
                if(msg.indexOf("Erro") > -1){
                    $('#ret_apaga_post').html(msg);                        
                }else{
                    $('#reload_post').html(msg);
                }

            }
        });
    });
});

The situation is that I have a list of data returned from the database, and I have a delete button for each record.

What happens is that depending on the return PHP, need to click on different Ivs. I found tips on msg.indexOf("Erro"), about jquery contains selector and also str.match(/Erro/), but only work the first time.

I also tried to add to ajax cache: false, also unsuccessful.

Thanks in advance.

2 answers

1

Some good practices I defined as my rules with AJAX:

  • Always send data through an object no matter the type of request (GET/POST/PUT...)
  • Always work with JSON data return

With just these two items, the url and handling the return of success, I do everything!

$(document).ready(function(){
    $('button').on('click',function(e){
        e.preventDefault();
        var codigo = $(this).attr('id');            
        $.ajax({
            type: 'post', 
            url: '<?php echo base_url('posts/apaga'); ?>',
            data: {'codigo': codigo},  
            dataType: 'json'              
            success: function(msg){
                if (msg.erro) {
                    $('#ret_apaga_post').html(msg);                        
                } else {
                    $('#reload_post').html(msg);
                }
            }
        });
    });
});

And now your backend has to return a type of data in JSON, try this:

public function apaga() {
    $dados = array(
        'erro' => true,
        'mensagem' => 'Houve um erro :/'
    );
    header('Content-Type: application/json');
    echo json_encode($dados);
}
  • Ah! And I advise avoid short tags with PHP, use <?php echo instead of <?=

  • Friend, thanks for the help, I saw, your code works, but it was not necessary. I just realized that my code is correct. My mistake was that I was changing the DOM and without using mutation observer or re-water the Jquery on the page, it stops working even.

  • Perfect, I didn’t really realize there were problems, just not following the pattern I recommend, but that’s not why it wouldn’t work :)

  • Do you have any alternative to mutation observer? I think the code too big and I didn’t even feel like using, at the moment I choose to always reload the javascript on the page, but seems to gambiarra right.

  • AH! Thank you for sharing this about the mutation observer I have always had this kind of problem that is not very clear in the question (or I that does not work well in the morning kkk), but I understood. Tell me more about how you solved your problem!!

0

More detailed example of the problem, actually the code in the question is correct, the problem is that when reloading via ajax part of DOM, this new piece of code remains invisible to the jquery that has just been used.

Not to wear the blessed one mutation observer, I’d rather give reload in jquery, example:

<div id='div_reload_sempre'> <input type='text' value='pode ser apagado 1'> <button id='id_input_1'>1</button> <br> <input type='text' value='pode ser apagado 2'> <button id='id_input_2'>2</button> </div>

//essa div acima, tem uma cópia exata apenas do conteudo dela em outro arquivo `php` por exemplo com nome `conteudo_div_reload`

<div id='recarrega_este_js'> <script> $('button').on('click',function()){ //aqui vão parametros ajax normal como na pergunta success: function(msg){ $('#div_reload_sempre').html('conteudo_div_reload'); //aqui acima, vai recarregar a div, com os dados que ficaram apos o delete, ou seja la o que fizerem $('#recarrega_este_js').html('conteudo_desse_script'); //aqui acima, esse jquery tem de ser recarregado após o delete feito, senao no proximo botão que for clicado, pro jquery, ele não existe mais } } </script> </div>

//mesma coisa para o script, tem de ter um outro arquivo com esse conteúdo nele
//nesse caso eu salvo esse conteudo dentro de um arquivo `php` mesmo, achei mais prático que um `js` por causa do framework que uso

Browser other questions tagged

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