Event Listenter and Ajax

Asked

Viewed 37 times

0

Guys, this is my first post. I’m sorry if I didn’t follow some rule/publication label.

I made an html form that sends data to a php file. Then I put ajax so I don’t have to re-load the pag. So far ok. But html and ajax are in the same scrip and I want to separate them.

The form has a button to answer. 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. It is possible to do this?

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 ajax inside addeventlistener when the click happens and then separate the files. How can I do this?

1 answer

0

You can use jQuery to do this by using the method .on(), 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>
  <button id="ajax-button">Clique-me!</button>
</form>

  • I couldn’t do :( I put it in another file . js this here: <script> $("#botao_resp_<?= $Row['id']? >"). on('click', Function(Event) { Event.preventDefault(); Alert('You clicked the! '); $. ajax({ method: 'POST', url : 'database-reply.php', date: { id : $("#id-answer-<?= $Row['id']? >"). val() , answer : $("#answer-question-<?= $Row['id']? >"). val() } }). done(Function(data){ console.log($("#card-<?= $Row['id']? >"). Hide(); Alert("Answered Successfully!" ); }). fail(Function(){ Alert('Screwed up'); }); Return false; }); </script>

  • I imported it into html: <script src="main.js" ></script> E in the console it appears this: Uncaught Error: Syntax error, unrecognized Expression: #botao_resp_<?= $Row['id']?>

  • In the javascript file you should not include the tags <script> and </script>.

  • I took the tags and nothing yet.

Browser other questions tagged

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