I would like to clear the inputs after the user submit the form using ajax.
My code works fine, i made based tutorials and after send fields are still with values. I want to clean them.
<script type="text/javascript">
$(document).ready(function(){
$("#inserir").click(function(){
$('#loadingDiv')
.hide()
.ajaxStart(function() {
$(this).show();
})
.ajaxStop(function() {
$(this).hide();
})
;
var nome=$("#nome").val();
var email=$("#email").val();
var confirmacao=$("#confirmacao").val();
var acompanhantes=$("#acompanhantes").val();
// loading image
$("#message").html('<center><img src="images/ajax.gif" /></center>');
$.post('inserir.php', {nome: nome, email: email, confirmacao: confirmacao, acompanhantes: acompanhantes},
function(data){
$("#message").html(data);
$("#message").hide();
$("#message").fadeIn(500);
});
return false;
});
});
</script>
Php
$nome = $_POST['nome'];
$email = $_POST['email'];
$confirmacao = $_POST['confirmacao'];
$acompanhantes = $_POST['acompanhantes'];
//Insert Data into mysql
$query=mysql_query("INSERT INTO cadastro_rsvp(nome,email,confirmacao,acompanhantes,id) VALUES('$nome','$email','$confirmacao','$acompanhantes','')");
mysql_close($con);
if($query){
echo "Dados enviados";
}
else{ echo "Erro!"; }
}
An example using one of your fields:
$("#nome").val('');
The above code will basically blank whatever is in the textfield.
I use HTML to do it.
<button type="reset" value="Reset">Reset</button>
This will clear all textbox, textarea, radio button, checkbox values: replace "#myFormId" with your form id.
$('input:text, input:password, input:file, select, textarea', '#myFormId').val('');
$('input:checkbox, input:radio', '#myFormId').removeAttr('checked').removeAttr('selected');
you must add it after this line in your code:
$("#message").fadeIn(500);
If you want to clear your fields AFTER you save it into the database, you'll have to clear your inputs AFTER you get a response from the server, in this case, in the success
of your $.post
.
$.post('inserir.php',
{nome: nome, email: email, confirmacao: confirmacao, acompanhantes: acompanhantes},
function(data){
$("#message").html(data);
$("#message").hide();
$("#message").fadeIn(500);
//HERE YOU PERFORM THE RESET (I suppose that they are input text fields):
$("#nome").val('');
$("#email").val('');
$("#confirmacao").val('');
$("#acompanhantes").val('');
});
return false;
});
Also, check the jQuery.post documentation for more information to work directly with a success callback function.