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?
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>
– Guilherme
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']?>
– Guilherme
In the javascript file you should not include the tags
<script>
and</script>
.– Luiz Felipe
I took the tags and nothing yet.
– Guilherme