まず、昨日始めたばかりのAJAXを使用するのは初めてです。
これが私のコードです:
<?php
if (isset($_POST['number1'],$_POST['operation'],$_POST['number2'])) {
$number1 = trim(strip_tags($_POST['number1']));
$number2 = trim(strip_tags($_POST['number2']));
$operation = $_POST['operation'];
if ($operation == "plus") {
$answer = $number1 + $number2;
$operation = "+";
}
if ($operation == "minus") {
$answer = $number1 - $number2;
$operation = "–";
}
if ($operation == "multiply") {
$answer = $number1 * $number2;
$operation = "×";
}
if ($operation == "divide") {
$answer = $number1 / $number2;
$operation = "÷";
}
$output = '<br /><center><div id="success"><span style="color: orange; font-size: 20px;">'.number_format($number1).'</span> <span style="color: blue; font-size: 24px; font-weight:bold;">'.$operation.'</span> <span style="color: orange; font-size: 20px;">'.number_format($number2).'</span> <span style="color: blue; font-size: 24px; font-weight:bold;">=</span> <span style="color: purple; font-size: 20px;">'.number_format($answer).'</span></div>
';
echo $output;
die();
}
?>
<form method="POST" id='calculatorForm'>
<input type="number" name="number1" id="url" placeholder="Enter your first number" autofocus required />
<br />
<select name="operation" id="url" style="width:100%;">
<option value="operation">Select A Operation:</option>
<option value="plus">Plus</option>
<option value="minus">Minus</option>
<option value="multiply">Multiply</option>
<option value="divide">Divide</option>
</select>
<br />
<input type="number" name="number2" id="url" placeholder="Enter your second number" required />
<input type="submit" class="enter" id="submit" name="submit" value="Calculate!">
<br />
<span style="font-size:40px;color: purple;font-wight: bold;">Result: <span id='result'>0</span></span>
</form>
<script>
$('#calculatorForm').submit(function(){
var num1 = $('input[name="number1"]').val();
var oper = $('select[name="operation"]').val();
var num2 = $('input[name="number2"]').val();
$.ajax({
type: "post",
data: {number1: num1, operation: oper, number2: num2},
success: function(data){
$('#result').html(data);
}
});
return false;
});
</script>
フォーム送信を使用してページでこのコードを実行しようとすると、フォームの下にページ全体が表示され、入力内容は計算されません。