I'm trying to post some data to post.php
and I want the result to display in form.html
, I used Ajax to get php output without needing to reload the page, what I couldn't figure out is how to flush some of the php output before the php script finishes.
I tried flush()
and ob_flush()
but it seems that they don't work when used with Ajax. My goal is to update form.html
in real time without reloading the page.
Here is an example of what I'm trying to achieve. Source Code:
form.html
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#myform").validate({
submitHandler: function(form) {
// do other stuff for a valid form
$.post('post.php', $("#myform").serialize(), function(data) {
$('#results').html(data);
});
}
});
});
</script>
</head>
<body>
<form name="myform" id="myform" action="" method="POST">
<!-- The Name form field -->
Name:
<input type="text" name="name" id="name" size="30" value=""/>
<br>
<!-- The Email form field -->
Email:
<input type="text" name="email" id="email" size="30" value=""/>
<br>
<!-- The Submit button -->
<input type="submit" value="Submit"/></div>
</form>
<!-- Result goes here -->
<div id="results"><div>
</body>
</html>
post.php
<?php
for($i=0;$i<2;$i++) {
echo "Your Name is ".$_POST['name']. "<br/>";
echo "Your E-mail is".$_POST['email']."<br/>";
echo "Waiting 2s <br/><br/>";
//I want to print the above before waiting 2 seconds.
sleep(2);// in real application this will be equivalent of some calculation that takes time.
}
?>