Event Listenter and Ajax

0

Well, this is my first post. Sorry if I did not follow some publishing rule / tag.

I made a form in html that sends data to a file in php. Then I put ajax not to reload the page. Until then, okay. But the html and ajax are in the same scrip and I want to separate them.

The form has a reply button. So I thought I'd do it in the js file. a querySelector with the form id and addEventListener, and when the click occurred, it would execute ajax. Is it possible to do that?

1 - Ajax

<script>
    $(document).ready(function(){   

    $("#form_resp_<?=$row['id']?>").submit(function(e){
    //event.preventDefaut();

    $.ajax({
        method: 'POST',
        url : 'banco-responder.php',
        data: {
        id : $("#id-resposta-<?=$row['id']?>").val() ,
        resposta : $("#resposta-pergunta-<?=$row['id']?>").val()
    }
        }).done(function(data){
        console.log($("#card-<?=$row['id']?>").hide());
        alert("Respondido com Sucesso!");
        }).fail(function(){
        alert('Deu pau');
        });
    return false;
        });
    });
</script>

2 - Query Selector / addEventListener:

<script>                            
    var botaoResponder = document.querySelector("#botao_resp_<?=$row['id']?>");
    botaoResponder.addEventListener("click", function(){
        alert("teste: Botão responder foi clicado com sucesso!!!");

    });
</script>

I want to put the ajax inside the addEventListener when the click happens and then separate the files. How can I do this?

    
asked by anonymous 27.01.2018 / 13:25

1 answer

0

You can use jQuery to do this by using the .on() method, for example:

/** Seu arquivo JavaScript separado. */

(function ($) {
  'use strict';
  
  $(function () {
    $('#ajax-button').on('click', function () {
      alert('Você clicou no botão!');
      
      /** Do stuff. */
    });
  });
})(jQuery);
<!-- Seu arquivo HTML -->

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><form><buttonid="ajax-button">Clique-me!</button>
</form>
    
27.01.2018 / 13:39