Reputation: 1
this is my code for for submitting my form: aj.js $(document).ready(function(){
$("#reqForm").submit(function(e){
e.preventDefault();
var f = e.target,
formData = new FormData(f),
xhr = new XMLHttpRequest();
xhr.open("POST", f.action,true);
xhr.send(formData);
xhr.onreadystatechange=function()
{
if (xhr.readyState==4 && xhr.status==200)
{
$("#alert").html(xhr.responseText);
$('#alert').css('visibility','visible').fadeOut(5000);
}
}
});
});
at the first time when submit the form, all things is good and all mycode run well. but when i want too submit for the second, third ,.. time the ajax code done and form data save in database, but this part of my code doesnt work
xhr.onreadystatechange=function()
{
if (xhr.readyState==4 && xhr.status==200)
{
$("#alert").html(xhr.responseText);
$('#alert').css('visibility','visible').fadeOut(5000);
}
my insert file:
$result=mysqli_query($dbCnn,"insert into request (name,telNum,email,request,date) values('$_POST[name]',$_POST[tel],'$_POST[email]','$_POST[request]',NOW())");
if(mysqli_affected_rows($dbCnn)<1)
$_SESSION['alert']="success!!";
else
$_SESSION['alert']="NOT!";
echo $_SESSION['alert'];
}
?>
Upvotes: 0
Views: 67
Reputation: 3873
it is very clear that xhr.onreadystatechange
is not firing after the first time.
I am not sure if this is the solution. but the way you registered the form submission could have an impact.
So try linking the submit event to the root document so that it will bubble every time you submit and reload , like this
$(document).ready(function(){
$(document).on("submit","#reqForm",function(e){
e.preventDefault();
var f = e.target,
formData = new FormData(f),
xhr = new XMLHttpRequest();
xhr.open("POST", f.action,true);
xhr.send(formData);
xhr.onreadystatechange=function()
{
if (xhr.readyState==4 && xhr.status==200)
{
$("#alert").html(xhr.responseText);
$('#alert').css('visibility','visible').fadeOut(5000);
}
}
});
});
I hope that will work out
answer is inspired from : Submitting a form with jQuery/Ajax only works every other time
========== EDIT:
There are some thoughts on SO answers that the order does matter, so you first open()
the Ajax request then set your event xhr.onreadystatechange=function()
then use send()
If what I read is true then it should work
Try it and let me know
Upvotes: 0