The way I think about your problem is similar to what you described it: do a double calculation. And I think the big boys do it.
Example: add two numbers. So you have this code:
HTML snippet:
<form method="post" action="/add.php"> <input id="firstOperand" name="firstOperand" placeholder="First operand"/> <input id="secondOperand" name="firstOperand" placeholder="Second operand"/> <input type="submit" onclick="doCalculation()" value="Add"/> </form> <div id="result" />
Your JS might look like this:
function doCalculation() { var first = parseInt(document.getElementById('firstOperand').value); var second = parseInt(document.getElementById('secondOperand').value); var result = first + second; // the minimum amount of error checking if isNan('result') return false; document.getElementById('result').innerHTML = result; // Now use some framework (like jQuery) to make an Ajax call and pass the result to callback. Framework.Ajax('/add.php?format=json', 'POST', {first: first, second: second}, callback); return false; } function callback(response) b var res = response.json.result; var resultEl = document.getElementById('result'); var errorEl = document.getElementById('error'); // if our result is not correct, we want to update the user on it if (res != parseInt(resultEl.innerHTML)) { Framework.removeClass(errorEl, 'hidden'); } document.getElementById('result').innerHTML = res; }
Of course, your PHP results page (add.php) will return json with the result. The added value here is that you can also return a simple HTML result (for example, if js is disabled).
Your callback can also check if there was an error in the returned result and display this error message. Or, if the result expires, display a notification that the "result" is not saved. But this is beyond the scope of the question, I think (at least, outside the scope of the answer).
Note: this is only the code from the top of the head, and not tested, written directly in the response window, maybe several things should be done better.
source share