Board index   FAQ   Search  
Register  Login
Board index php forum :: php coding PHP coding => General

How can I create a calculator withouth reloading page?

Ask about general coding issues or problems here.

Moderators: macek, egami, gesf

How can I create a calculator withouth reloading page?

Postby fjpremier » Fri Mar 28, 2014 9:33 am

I did a simple calculator where the user inputs a value and they hit summit and gives them the result.

/* Calculator For Competition Arena with high traffic.*/

$width = htmlentities($_POST['width']);
$length = htmlentities($_POST['length']);

$squarefoot= $width*$length;
$total = $squarefoot*.75;
$totalprice = $total *.82;

This is what I got, so far I been able to reload the page (after getting inputs and clicking submit) and take the user to the div where the calculator is. Is annoying that every time the hit summit the pages reloads. How can I make it so it just gives the result?

<h2>Calculate the price for your Arena</h2>
<form action="calculator.php#section2" method="post" >
<div id="width" style="float: left; margin-right: 14px;">
Enter width in feet: <input type = "text" name="width"><br>
<div id="length">
New php-forum User
New php-forum User
Posts: 1
Joined: Fri Mar 28, 2014 9:26 am

Re: How can I create a calculator withouth reloading page?

Postby seandisanti » Fri Mar 28, 2014 11:15 pm

If you don't want to reload the page, you have to use ajax. Ajax via jquery is probably the easiest way. give me a second and I'll whip up a quick example.

Here you go, comments thrown in for quick explanation, but it's pretty straightforward.

Code: Select all


// This is an example of using AJAX to handle a form submission without reload.
// Because we're using a single page for both parts, use $_POST as a control 
// variable so we know which way the page is being used.
    if (!$_POST){
        // if no post, then we're not handling a form; include jquery.
        echo '<script src=""></script>';
// simle form
        echo '<form name="calc">';
        echo 'Enter a simple formulat: <input type="text" name="calculation" id="calculation" />';
        echo '<input id="Abutton" type="button" value="=" /></form>';
        // somewhere to put the answer:
        echo '<span id="answer"></span>';
// jquery ajax call to submit the formula on the backend and wait for response
                          f = $("#calculation").val();
} else { //there's post data! lets process it
        $input = $_POST['calculation'];
        $input = preg_replace('/[a-z]/i','',$input); //this is just to remove letters
        echo 'the problem is ' . $input; //you can do the math, i'm just answering your question
php-forum Fan User
php-forum Fan User
Posts: 838
Joined: Mon Oct 01, 2012 12:32 pm

Return to PHP coding => General

Who is online

Users browsing this forum: Bing [Bot] and 2 guests

Sponsored by Sitebuilder Web hosting and Traduzioni Italiano Rumeno and antispam for cPanel.