0

I am trying to make a simple calculator like this :

input1 select input2 = input3

  • input1,input2 is first and second value
  • select have 4 operator : + - * /
  • input3 show the result

This is my code and it doesnt work as expected,can someone help me out ?

<?php
ini_set('display_errors', 0);
session_start();

/*  Check if form is submit 
 *  if any input field is empty --> "NaN" result
 *  else check value of select field --> do the math --> result
 *  Then call JS function to change value of result field
 */ 

if(isset($_GET['act']) && $_GET['act']== 'do')  {

    $val1 = $_GET['val1'];
    $val2 = $_GET['val2'];
    $oper = $_GET['oper'];
if($val1 == NULL || $val2 == NULL)  
    $result= "NaN";
else    {
    switch($oper)   {
        case 1 : $result= $val1 + $val2; break;
        case 2 : $result= $va1l - $val2; break;
        case 3 : $result= $val1 * $val2; break;
        case 4 : $result= $val1 / $val2; break;
    }
}
echo "<script> showResult('".$result."') </script>";
}
?>

<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<style>
input,select { height:30px;width:50px}

</style>



</head>
<body>
<form method="GET" action="bai4_1.php?act=do">
    <table>
    <tr><td>Op1</td>
        <td>Oper</td>
        <td>Op2</td>
        <td>Result</td></tr>
    <tr><td><input id="val1" type="text" name="val1" value="<?php echo 
$_GET['val1'];?>"/></td>
        <td><select id="oper" name="oper">
            <option value=1>+</option>
            <option value=2>-</option>
            <option value=3>*</option>
            <option value=4>/</option>
            </select></td>
        <td><input id="val2" type="text" name="val2" value="<?php 
echo$_GET['val2'];?>"/> =</td>         
        <td><input id="result" type="text"></td></tr>
    </table>
</form>
</body>
</html>


<script>
$("input,select").change(function(){
setTimeout(function(){
    $("form").submit();
},1000);
});

function showResult(result) {
$("#result").val(result);
}   
</script>
7
  • 4
    "it doesnt work as expected" - Can you be more specific? Commented Mar 5, 2013 at 14:49
  • 1
    Why do this on the server? Commented Mar 5, 2013 at 14:49
  • 3
    Doesn't work... how? wrong result? doesn't do anything? Kicks your dog? insults your mother? You should not be outputting anything BEFORE the <html> tag, however. you're building an invalid page. Commented Mar 5, 2013 at 14:50
  • 1
    @mplungjan If I had to venture I guess I'd say this is homework based on the name of his script: bai4_1 sounds like a class and assignment name. Commented Mar 5, 2013 at 14:53
  • 1
    To add on to what @MarcB said you should also not being outputting after the closing HTML tag. Commented Mar 5, 2013 at 14:53

2 Answers 2

2

First know what languages you want to use for you application.

I see you use PHP, HTML, JavaScript and jQuery.

But if you rethink your small application, you will (maybe) notice that you can do all your actions client side. So you could trow away your PHP.

So now we need HTML to display a form.

<form>
    <table>
        <tr>
            <td>Op1</td>
            <td>Oper</td>
            <td>Op2</td>
            <td>Result</td>
        </tr>
        <tr>
            <td>
                <input id="val1" type="text" name="val1" value="" />
            </td>
            <td>
                <select id="oper" name="oper">
                    <option value="+">+</option>
                    <option value="-">-</option>
                    <option value="*">*</option>
                    <option value="/">/</option>
                </select>
            </td>
            <td>
                <input id="val2" type="text" name="val2" value="" />
            </td>
            <td>
                <input id="result" type="text" />
            </td>
        </tr>
        <tr>
            <td></td>
            <td></td>
            <td></td>
            <td>
                <input type="submit" />
            </td>
        </tr>
    </table>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

In your HTML I edited some things:

  • I added an input type="submit", we can't assume the user is able to send the form without.
  • Also I change the values of your select box

Now the form is ready.

With a little knowledge about jQuery we can easily catch the submit event.

$('form').submit(onFormSubmit)

function onFormSubmit() {
    var val1 = $('#val1').val()
    var val2 = $('#val2').val()
    var operator = $('#oper').val()

    $('#result').val(eval(val1 + operator + val2))
    return false
}

Explained above, I have an event listener on the from.

After submit I get the 3 values.

I use eval to use strings as code, that way I can do eval(val1 + operator + val2)

I hope this will help you.

Include a jsFiddle example here.

Sign up to request clarification or add additional context in comments.

4 Comments

He might be using PHP because he got told to, if it's homework, or because he knows he'll be supporting users who don't have JS enabled... Maybe I'm (too) pedantic, but I'm still in the camp that JS should enhance, not replace, content
@ChrisW First, He uses jQuery so I gues he use JavaScript. Second in year 2013, you need to enable javascript, if you dont you probably have a lot of corrupt pages. Google: Please enable JavaScript to use the Doodle Finder. Facebook: For a better experience on Facebook, enable JavaScript in your browser, or switch to our mobile site. and even boilerplate pushes chromeframe to your browser. And don't even try to use HTML5 without JavaScript. I gues you are too oldschool ;)
Yes - facebook do have a version which works without JS, and so they are enhancing content with it, but all content is still visible without it. This is the approach I was taught, and still use. I know it's oldschool, but I'm happy being oldschool if it makes for better user experience. My phone, for example, doesn't handle JS well, so I purposefully look at sites I know don't use JS, meaning other sites I do use on a desktop lose out.
Tks guys! This is not a homework but an exercise I found and Im studying PHP by myself. I want to ask you guys 1 more thing? : - How to set the value of input field by PHP NOT Javascript ? Is that possible ?
0

You are probably getting a JavaScript error when you load your page. Currently, the source code output of your page probably looks like this:

<script> showResult('".$result."') </script>
<html>
...
</html>
<script>
...
function showResult(result) {
$("#result").val(result);
}   
</script>

There are two problems here:

You shouldn't have anything, even <script>, outside of your <html> tags.

You can move this stuff into the <head> tags so make it look and work nicer. It's considered bad practice to put things outside of the <html> tags.

You are calling your JavaScript function before you define it.

The first JavaScript line tries to execute your ShowResult function. However, this hasn't been defined yet (it's defined at the bottom of the page, and JavaScript hasn't read it yet), so it doesn't know what to do. This causes an error. If you are using Google Chrome or Firefox, then you can view this error message by hitting Control-Shift-J.

The Fix

First, move all of your JavaScript code into the <head> of your page.

Second, write your functions first. This will define them as the page loads, so everything is available once you start executing functions.

Third, when you use jQuery, wrap your function execution code (i.e.: showResult('".$result."')) in this code:

$(document).ready(function() {
    // put your code here
});

This will instruct your code to wait for the entire page to load before starting to execute any JavaScript.

The result should look something like this:

<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
//  define your functions up here
function showResult(result) {
    $("#result").val(result);
}  

//  define your Procedural code here. This stuff will execute once the page loads completely:
$(document).ready(function() {
    $("input,select").change(function(){
    setTimeout(function(){
        $("form").submit();
    },1000);
    });

    <?php if($result != "NaN") {
    //  Show this code only if $result is defined and valid:
echo "showResult('".$result."');";
?>
});
</script>

2 Comments

Tks guys! This is not a homework but an exercise I found and Im studying PHP by myself. I want to ask you guys 1 more thing? : - How to set the value of input field by PHP NOT Javascript ? Is that possible ?
First, create a variable and set it to blank: $value = '';. Then, if the inputs that you received are ok, set the value (basically, set it using your switch statement). Finally, do what you did with the other inputs: <input id="result" type="text" value="<?php echo htmlspecialchars($value);?>" />. If this is your first time loading the page (or if the user typed a as their first number or something), then the input will be blank. Otherwise, it will show the final number. FYI: htmlspecialchars() is a security function that you should always use when writing any user submitted text.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.