2
I’m trying to send merged data from a form + PHP variables to be inserted into the BD, without there being page refresh.
For this, I have a simple html form, and a PHP conditional that checks the Submit click of this form (that’s because I have other submits on the same page). Inside IF, I inserted my AJAX to take this data to the file that I would write to BD.
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 processes.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 filled 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 processes.php, as there is no recording in the BD and neither displays Alert of the data by Ajax. Where is the error?
on the refresh, I’ve already changed to
e.preventDefault();
but, as you said yourself, it didn’t work. Now, I don’t know exactly how to use theserialize()
, because not only do I have form data, but I take all the data and convert it into PHP variables (because most come from the PHP block). How could it be in this case?– Atoyansk
In this case, you could do it in two ways, the first way is simpler. You can include fields
<input type='hidden' value='<?php echo $variavel_php ?>'>
and make it serialize. The other way, is you put the variables in an array and turn into a JSON, and the javascript file use the functiongetJSON()
from jQuery to take these values and after that make the ajax request.– Guilherme Lopes