开发者

How would I do this in PHP? Form input, then function, then output in div, without page refresh?

index.php

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Form submit in php without refresh?</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script type="text/javascript">
function processForm() { 
        $.ajax( {
            url: process.php,
            data: 'how to get everything from process.php echos?',
            success: function(data) {
                $('#calc').html(data);
            }
        } );
}
</script>

</head>
<body>
    <form id="form" method="post" action="" onsubmit="processForm();return false;">
        <input type="text" id="total" name="total" value="" />
        <input type="submit" value="Submit" id="submitButton" />
    </form>
<div id="calc">
</div>
</body>
</html>

process.php

<?php
$number = $_POST['total'];
//this should be $number = "the number entered in the 'total' field in the form";
开发者_高级运维
echo $d = ceil(log(2*$number)/log(3))," tiers<br />\n";
$x = 1;
for($i = 1; $i<$d;$i++){
    echo "tier " . $i . "<br />\n";
    echo str_repeat('o', $x),"<br />\n";
    $number -= $x;
    $x *= 3;
}
echo "tier " . $i . "<br />\n";
echo str_repeat('o', $number),"<br />\n";
//all of the above echos should go into the 'calc' div in html, without page refresh
?>


You will need to do an AJAX call instead of actually doing an HTTP POST. This is done in JavaScript. You then hang code off the return hook to put content in the div.

jQuery has library calls to make this easier than doing it all manually.


There are two things to cover here.

1) Retrieving POST data.

You can access the post data from the $_POST array, so in your case you would do $number = $_POST['total'];

2) Ajax call

Here is a good tutorial on using jQuery for submitting forms without redirect:

http://net.tutsplus.com/tutorials/javascript-ajax/submit-a-form-without-page-refresh-using-jquery/

And here is the API for jQuery Ajax methods: http://api.jquery.com/category/ajax/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜