2
The code in Ajax works perfectly but the data is not sent to php! Where am I going wrong?
AJAX.php
<!DOCTYPE html>
<html>
<head>
<title>AJAX</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-3.4.1.min.js"></script>
<script type="text/javascript" src="AJAX.js"></script>
<style>
.comments{
margin-left:400px;
width: 400px;
}
</style>
</head>
<body>
<div class="cadastro">
<form id="form-msg" method="post" enctype="multipart/form-data">
<fieldset>
<p>
<span>Digite seu comentário:</span>
<input type="textbox" id="mensagem">
<button type="button"> Clique </button>
</p>
</fieldset>
</form>
</div>
<p>Comentários</p>
<span id="aqui"></span>
</div>
</body>
</html>
AJAX_ACTION.php
<?php
$mensagem = $_REQUEST['mensagem'];
echo $mensagem;
AJAX.js
$(document).ready(function () {
$("button").click(function(){
var mensagem = $('#mensagem').val()
if (mensagem == ''){
alert("Comentário não pode ser vazio")
}
else{
$.ajax({
type: 'POST',
url: "AJAX_ACTION.php",
data: {
mensagem: mensagem,
},
dataType: "json",
success:
$("#aqui").append("<br>").append(mensagem),
done:
$("#mensagem").val(''),
});
}
});
});
How do you know you’re not sending?
– Sam
I tried to change the Ajax url to "AJAX.php" and put the php code there, even then nothing happens, echo $message never prints anything.
– Pedro Henrique
I’ll rearrange everything for you. And then you’ll be readapted for your project ok?
– user148170
Okay! Actually it’s just another test...
– Pedro Henrique
@Pedrohenrique check if it worked,
– user148170
The problem is that you specified that the answer would be a JSON and your php returns a string without the JSON format that is refused. Put
dataType: "text"
who accepts.– Augusto Vasques