views:

113

answers:

7

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)?

+3  A: 

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

Skilldrick
+1 for SSJS. http://www.jaxer.org/ is a nice one..
Ramesh Vel
+1  A: 

A partial solution is AJAX. For example, write your validation code once on the server, and let your forms talk to the server to see if an input is valid and ask for an error message to display if not.

Nathan Long
although (unless you are just talking about sharing the code but still doing validation on both sides) this assumes that JavaScript is enabled/available
AJM
A: 

json_encode and json_decode are a great start - the same source of data available in php arrays and json objects as required.

the json_encoded data can be served through <script> tags or ajax as you see fit.

Ken
+2  A: 

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.

Pepijn
A: 

Do fast validation client-side (like pattern-matching, date&number correctness) and security check server-side.
Also you can use AJAX to do server-side validation but this way you can have a responce gap between user input and validation result. So use JavaScript for fast and basic validation and do heavy one with PHP.

NilColor
A: 

You could use http://phpjs.org/ to run you php code on the client side. This works for most functions in php.

Matthew
A: 

You may try to use haxe language. It could be translated in js/php and even actionscript (flash).