I'm trying to send merged data from a form + PHP variables to be inserted into the DB, without refreshing the page.
For this, I have a simple html form, and a PHP conditional that checks the submit form's click (this is why I have other submits on the same page). Inside the IF, I inserted my AJAX to take this data to the file it would write to the DB.
The HTML form:
<form id="textoResp" action="" method="post">
<label for="textoResposta">Digite sua resposta abaixo:</label>
<textarea name="textoResposta" required></textarea>
<input type="submit" name="text" />
</form>
The PHP snippet with Ajax is:
<?php
if(isset($_POST['text'])):
$id_servico = $_GET['servico'];
$id_sessao = $_GET['id'];
$id_pergunta = $r['id'];
$id_user = $_SESSION['usrid'];
$texto = $_POST['textoResposta'];
?>
<script type="text/javascript">
$(document).ready( function(){
$("#textoResp").submit( function() {
$.ajax({
type:'post',
url:'processa.php',
data:{ 'id_servico': <?php echo $id_servico; ?>, 'id_sessao': <?php echo $id_sessao; ?>, 'id_pergunta': <?php echo $id_pergunta; ?>, 'id_user': <?php echo $id_user; ?>, 'texto': <?php echo $texto; ?> },
success: function( data )
{
alert( data );
}
});
return false;
});
});
</script>
<div class="status"><?php echo "Resposta Enviada!";?></div>
<?php
endif;
?>
And the file process.php, which would receive the data:
<?php
$nid_servico = $_POST['id_servico'];
$nid_sessao = $_POST['id_sessao'];
$nid_pergunta = $_POST['id_pergunta'];
$nid_user = $_POST['id_user'];
$ntexto = $_POST['texto'];
$link = mysql_connect("localhost", "root", "");
mysql_select_db("db", $link);
$sql1="INSERT INTO resposta(id_servico, id_sessao, id_pergunta, id_user, texto) VALUES ('$nid_servico', '$nid_sessao', '$nid_pergunta', '$nid_user', '$ntexto')";
$executa_sql=mysql_query($sql1) or die(mysql_error());
?>
What happens when I run this page: the data is populated in the Ajax code block in the browser, but the page gives refresh (the line "return false;" would be to prevent refresh), and apparently the data does not arrive until PHP processesa.php, because there is no write in the DB and it does not display alert of the data by Ajax. Where is the error?