How can I create a calculator withouth reloading page?

Ask about general coding issues or problems here.

Moderators: macek, egami, gesf

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

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

Post by 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

<?php

// 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="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></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>
                $(document).ready(function(){
                      $("#Abutton").click(function(){
                          f = $("#calculation").val();
                        $.post("SinglePageCalc.php",{calculation:f},function(response){
                            $("span").text(response);
                        });
                    });
                });
        </script>';
        
                
    } 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
        exit;
}

Post Reply

Who is online

Users browsing this forum: Baidu [Spider], margoo and 1 guest