On ("Click") JavaScript does not work [duplicate]

2

I made a script to get the value of an element that is generated in php, whenever this element is clicked but it is not working

<script>
    $('.collection-item').on('click',function(){    
        var  idA = $(".collection-item").val();  
        alert("tete");  
        $.ajax({ 
            url: 'Chamadas/listarMunicipios.php', 
            type: 'POST', 
            data: { id: idA},
            success: function(data) { 

                window.location.reload(); 
            } 
        }); 

    });
</script>

Element

echo '<a href="#!" value="" class="collection-item">TESTE</a>';
    
asked by anonymous 26.09.2018 / 05:42

1 answer

0

Just in case someone comes to this page ..

The code is correct as exemplified by min below:

$('.collection-item').on('click',function(){    
        var  idA = $(".collection-item").val();  
        alert("funcionou");  
        $.ajax({ 
            url: 'http://www.json-generator.com/api/json/get/cdYItaXpvm?indent=2', 
            type: 'GET', 
            success: function(data) { 

                console.log(data);
            } 
        }); 

    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><ahref="#!" value="" class="collection-item">TESTE</a>

The problem is that it is generating a code using php, and the script needs to reference the document, so it is necessary to use:

$(document).on('click', '.collection-item'

In the jquery code.

You can also if you generate by php this code inside a function

// A $( document ).ready() block.
$( document ).ready(function() {
   //codigo do clik aqui dentro
});

or by using the short version:

// Shorthand for $( document ).ready()
$(function() {
    //codigo do clik aqui dentro
});

link to a previously created question and answer

What is the difference between .on ("click", function () {}) and .click (function () {})?

Another interesting thing

It is not recommended to use php to generate the view, there are new architectural standards that we advise to create something more modular, separating the front of the backend, leaving all independent. a well used pattern is the restAPI insert the link description here

    
27.09.2018 / 20:18