I am trying to add ajax into my form so I can submit the form without refreshing, however the php echo command is not working. if I take out the ajax it works fine but refreshes on submission. I think it’s a case of trying to get them to work together. I am just learning ajax right now so I dont really know much about it all. Please take a look to see where I’m going wrong
<script type="text/javascript"
src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$('form').bind('submit', function(){
$.ajax({
type: "POST",
url: "ajax.html",
data: $("form").serialize(),
success: function() {
alert("form was submitted");
}
});
return false;
});
});
</script>
<?php
if(isset($_POST['submit'])){
$a=$_POST['a'];
$b=$_POST['b'];
echo $a.$b;
}
?>
<html>
<form method='POST'>
first name:<input type="text" name="a">
last name: <input type="text" name="b">
<input type='submit' name='submit'>
</form>
</html>
It’s probably worth noting that your echo’d PHP code will not be visible, since the ajax response will be getting that information. This isn’t a good example of how to use ajax, since you’re not displaying your result from the ajax call. Something like this would make more sense:
“ajax.php” PHP file: