Php/javascript Validated Calculation
Solution 1:
ajax?
you can pass all the variable entered with javascript and leave the process server based.
or i misunderstand your question?
Solution 2:
The way I think about your problem is like you described it: do double calculation. And I believe that's how the "big boys" do it.
Example: Add up two numbers. So you have a code like this:
HTML snippet:
<formmethod="post"action="/add.php"><inputid="firstOperand"name="firstOperand"placeholder="First operand"/><inputid="secondOperand"name="firstOperand"placeholder="Second operand"/><inputtype="submit"onclick="doCalculation()"value="Add"/></form><divid="result" />
Your JS might look like:
functiondoCalculation() {
var first = parseInt(document.getElementById('firstOperand').value);
var second = parseInt(document.getElementById('secondOperand').value);
var result = first + second;
// the minimum amount of error checkingifisNan('result') returnfalse;
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);
returnfalse;
}
functioncallback(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 itif (res != parseInt(resultEl.innerHTML)) {
Framework.removeClass(errorEl, 'hidden');
}
document.getElementById('result').innerHTML = res;
}
Of course, your PHP result page (add.php) would return json with the result. The added value here is that you can also return a plain HTML result (like if js is disabled).
Your callback could also check if there was an error in the returned result and display that error message too. Or if the result times out, display a notification that the "result" is not saved. But that's out of the scope of the question, I guess (at least, out of the scope of the answer).
Note: this is just the code off the top of my head, not tested, written directly in the answer box, probably a few things should be done better.
Post a Comment for "Php/javascript Validated Calculation"