I am trying to submit the form without reloading the page itself using the jQuery, but the data is not showing up and the form is reloading, which is not needed.
jQuery code:
function submitFormData() {
var firstval = $("#first").val();
var second = $("#second").val();
//var operator = $("#myselect option:selected" ).text();
$.post("index.php",{first:first,second:second},
function(data){
$('#results').html(data);
$('#formcal')[0].reset();
});
}
THIS IS THE HTML CODE ON THE SAME PAGE(INDEX.PHP):
<form action="" id="formcal" method="post">
<input type="number" id="first" name="first" placeholder="number"/>
<select name="operator" id="operator">
<option value="add">+</option>
<option value = "subtract">-</option>
<option value = "multiply">*</option>
<option value = "division">/</option>
</select>
<input type="number" id="second" name="second" placeholder="number 2"/>
<input type="button" id="submitFormData" onclick="SubmitFormData();" value="Calculate"/>
</form>
<br>
<?php //if(!empty($_POST['first']) && !empty($_POST['second'])){
$number = $_POST['first'];
$number2 = $_POST['second'];
echo "Answer: ";
if($_POST['operator'] == 'add'){
$complete = $number + $number2;
echo " $number + $number2 = $complete";
}
if($_POST['operator'] == 'subtract'){
$complete = $number - $number2;
echo "$number - $number2 = $complete";
}
if($_POST['operator'] == 'multiply'){
$complete = $number * $number2;
echo "$number X $number2 = $complete";
}
if($_POST['operator'] == 'division'){
$complete = $number / $number2;
echo "$number / $number2 = $complete";
}
//}
?>
</div>
<div id="results">
</div>
Prevent the default action of the form submit.
You can use the onsubmit event on the form itself.