Search code examples
ajaxsymfony4

Sucess ajax function work when i load the page


I don't understand why my sucess function work alone without i click on the function after 2 sec i load the page.

{% block javascripts %} 
 <script>
  $.ajax({
       url : '{{ path('post_like', {'id' : article.id}) }}',
       type : 'POST',
       dataType : 'html',
       success : function(code_html, statut){ 
         $("#likeChange").replaceWith("hello world");
         console.log("test")
     },
       error : function(resultat, statut, erreur){
       }
    });
</script>
{% endblock %} 

the content i need to change

 <a id="likeChange">{{ article.likes | length }}<a>

this is the button to call function

 <a data-like="{{ article.id }}" id="ajax" class="btn" role="button"><img src="{{ asset('build/image/flecheup.png') }}"></img></a> 

Solution

  • I just don't do a function onClick

    {% block javascripts %} 
     <script>
    $(document).on('click', '#ajax', function(){
       that = $(this);
      $.ajax({
           url : '{{ path('post_like', {'id' : article.id}) }}',
           type : 'POST',
           dataType : 'html',
           success : function(code_html, statut, likes){ 
             $("#likeChange").replaceWith(likes);
             console.log("test")
         },
           error : function(resultat, statut, erreur){
           }
        });
        return false;
    });
    
    </script>
    {% endblock %}