Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I represent a formula in a way that is understood by both Javascript and PHP?

I'm writing a shopping cart in PHP, and part of its function is to calculate shipping for a given set of products. For users with Javascript enabled, I want to provide the smoothest experience possible by having an accurate shipping calculation done on the client side so that changes in the cart do not require page reloads or AJAX calls.

Currently I have a function in PHP that calculates the shipping charge, and another function in Javascript that mirrors its functionality. I'm concerned that the formula may change frequently, and having to rewrite two separate functions in two different languages (and make sure their outputs match) could create maintainability problems.

What I'm looking for is a way of representing the formula for calculating shipping charges in some language agnostic way, so that it can be interpreted by both PHP and Javascript. Currently the shipping formula is only a function of a single variable (number of items) although I would like the capability to add more without too much rewriting.

Is there an accepted way to represent a fairly simple mathematical formula in a way that can be interpreted by both PHP and Javascript? Preferably without writing my own interpreter?

Edit: I don't need a whole function, just a fairly simple mathematical formula along the lines of "4 + 1.5n". The kind of thing you would find in a typical spreadsheet cell.

like image 890
Robert Avatar asked Dec 30 '22 13:12

Robert


2 Answers

Generally, you are best off just to maintain two versions of the code. The most elegant solution, of course, is to write the server logic in JavaScript itself (see cappuccino.org); this would be a poor choice for you because it sounds like you have already written a ton of PHP code.

However, if you really feel the need to scratch this itch, consider an AJAX callback to the server. While slightly slower, most users will not notice.

like image 163
carl Avatar answered Feb 13 '23 23:02

carl


I would say do it on server side, and user AJAX, It won't make much of difference for user, but maintaining two versions can make a difference when user after submitting the order sees the different calculation.

Anyway if you due to some reason do not want AJAX at all, best way would be to have single javascript library which is executed both at client and server side. You may execute javascript from php on server side. e.g. you may use following from linuxto execute javascript

http://www.mozilla.org/js/spidermonkey/ http://www.mozilla.org/rhino/ http://www.wxjavascript.net/

see http://en.wikipedia.org/wiki/Server-side_JavaScript for more options

like image 44
Anurag Uniyal Avatar answered Feb 13 '23 23:02

Anurag Uniyal