How can I create a calculator withouth reloading page?

Ask about general coding issues or problems here.

Moderators: egami, macek, gesf

Post Reply
php-forum Fan User
php-forum Fan User
Posts: 974
Joined: Mon Oct 01, 2012 12:32 pm

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
        echo '<script>
                          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

Post Reply