<?php
$good = 0;
if($_POST['send']){
// handle submit
$good = 1;
}
?>
<html>
<head>
<title>example form</title>
</head>
<body>
<?php if($good == 1){ ?>
<p>Your form was submitted</p>
<?php }else{ ?>
<form action="" method="post" id="form">
<input type="text" name="text" id="text"><br>
<input type="submit" name="send" value="Send" id="send">
</form>
<?php } ?>
</body>
</html>
$good = 0;
if($_POST['send']){
// handle submit
$good = 1;
}
?>
<html>
<head>
<title>example form</title>
</head>
<body>
<?php if($good == 1){ ?>
<p>Your form was submitted</p>
<?php }else{ ?>
<form action="" method="post" id="form">
<input type="text" name="text" id="text"><br>
<input type="submit" name="send" value="Send" id="send">
</form>
<?php } ?>
</body>
</html>
This form can be ajawed easy with jQuery backed up with your original php code. Maybe you already noticed the id attributes of the form tags. That are the action trigger (send), the input value (text) and the placeholder (form).
The javascript that would be added is
$(document).ready(function(){
$("#send").click(function(){
$.post("process.php",{text: $("#text").val()},function(html){ $("#form").html(html); });
return false;
});
});
$("#send").click(function(){
$.post("process.php",{text: $("#text").val()},function(html){ $("#form").html(html); });
return false;
});
});
That's all. The click function catches the clicking of the button. Return false is added to stop the normal behaviour of the button.
The post function has three arguments; file, parameters and callback. The argument of the callback function can have any name you want and it gives back the output of the file. The file can output anything you want- html, xml, json - but html is the most easy option. The content inside the form tags is changed to the output of the file with the html function.
You can put your form handle code in a class method that you then call in the process.php as on the actual page to make your code less fault-prone. And it's best to add an action to the form tag.
No comments:
Post a Comment