There are a few edits you need to make to your js code.
(1) in your $(document).on('click', 'button.number', function () { you need to check if the current value is a .function (operator), and if so add the operator to memory before setting the value to the number. I used $.inArray($show.val(),['+','-','x','/']) !== -1 which checks to see if it is in the array.
(2) changing your $("#add").click(function () { to $(document).on('click', 'button.function', function () { allows you to use all your .function (operator) buttons for this code, and not just the +.
(3) you need to add the current value to memory before you post memory to your php.
(4) you need to change execute: $.show.val() to execute: memory
$(function () {
var $show = $('#display');
var currentDisplay = "";
$show.val(0);
$(document).on('click', 'button.number', function () {
if ($show.val().length >= 8) {
$show.val("Error");
} else if ($show.val() == "Error") {
$show.val("0");
}
// (1) check if current value is a .function
else if ($.inArray($show.val(),['+','-','x','/']) !== -1) {
var addOp = $show.val();
if (addOp) memory.push(addOp);
$show.val($(this).val());
}
else {
$show.val(($show.val() == "0" ? "" : $show.val()) + $(this).val());
}
});
$("#clear").click(function () {
$show.val("0");
});
$("#ce").click(function () {
if ($show.val().length >= 2) {
$show.val($show.val().substring(0, $show.val().length - 1));
} else {
$("#ce").trigger("click");
}
});
var memory = [];
// (2) changed from $("#add").click(function () { so all functions are registered
$(document).on('click', 'button.function', function () {
var addnum = $show.val();
if (addnum) memory.push(addnum);
$show.val($(this).val());
});
$('#equ').click(function () {
// (3) add current value to memory
var addnum = $show.val();
memory.push(addnum);
// (4) change execute: $show.val() to execute: memory
$.post("calculation.php", {
execute: memory
}, function (data,status) {
$show.val(data);
var e = memory.join('');
memory = [];
});
});
});
Then in calculation.php you want to loop through the array and add/subtract depending on the operator.
<?php
if(isset($_POST['execute']) && is_array($_POST['execute'])) {
$total = (int)$_POST['execute'][0];
for($i=1;$i<count($_POST['execute']);$i+=2){
switch($_POST['execute'][$i]){
case '+': $total += (int)$_POST['execute'][$i+1];break;
case '-': $total -= (int)$_POST['execute'][$i+1];break;
default : $total += (int)$_POST['execute'][$i+1];
}
}
echo $total;
}
else echo 'Error';
?>
(note: I only did + and - in php, assuming that you could figure out how to add the * and /)
here is an updated jsFiddle - http://jsfiddle.net/9t78jd47/3/ (it uses js code, instead of $.post() to mimic sending memory to calculation.php