Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Same code on browser/server

I'm writing a web app using PHP, and running into several situations where I need similar code on the server and browser. For example:

  • I want to validate user input, and generate the same error messages on both sides.
  • I want to format data using certain rules (e.g. if a given field is less than 1, show it with two decimal places, otherwise none), and have it appear the same regardless of which side renders it.

It seems like this should be a common problem, as people are moving more logic from the server to the browser. But are there any common patterns or libraries for dealing with it (particularly for PHP)?

like image 987
JW. Avatar asked Jan 26 '10 20:01

JW.


2 Answers

One solution would be to use server-side JavaScript. You'd be able to share huge chunks of code then.

like image 193
Skilldrick Avatar answered Nov 01 '22 10:11

Skilldrick


Interesting question! As far as I know there are 2 options for PHP:

  • Use Ajax to do form validation, so everything happens on the server.
  • There is this effort to bring PHP functions to JS, which should at least ease the porting: http://phpjs.org/

In Java however, you can run Javascript with Rhino.

The other things I can think of are ugly hacks with Flash or Java applets, or involve a framework like Pyjamas.

like image 31
Pepijn Avatar answered Nov 01 '22 10:11

Pepijn