1

I have a question about where to put the logic between jquery and php. I´m writing a small website where users can input different values. Those values are added together and multiplied with an value saved in a mysql database and outputed again to the user.

My question is whats the better way for doing this.

A: Let Jquery serialize the form and send all values to php. Php catches the Post vars and the value from the database, calculates everything, writes the sum to the database and gives everything back to the user.

B: When the User starts the Script the value of the Database is send from PHP to the User Form. Now Jquery does all calculations. When everything is ready, the Sum is send back to PHP and written in the Database.

The reason why I´m asking is A: seems to be safer with the validation of given values. But B: is more frindly to the server. (Jquery ajax is fired on Keyup, means the value would be queried from the database everytime the user edits the form.)

regards,

toni

Diodeus - James MacFarlane
  • 112,730
  • 33
  • 157
  • 176
Anatol
  • 1,923
  • 6
  • 26
  • 55
  • possible duplicate of [JavaScript: client-side vs. server-side validation](http://stackoverflow.com/questions/162159/javascript-client-side-vs-server-side-validation) – Quentin Jul 10 '12 at 11:31

2 Answers2

5

You should never trust the client. Always validate on the server, even if you do it on the client.

Validating on the client makes a better user experience because it does not require a trip to the server.

Validating on the server ensures the user has not tampered with the data.

In short: do both.

Diodeus - James MacFarlane
  • 112,730
  • 33
  • 157
  • 176
  • okay thank you. I thought about this. To not fire a mysql select everytime the user inputs something i could save the value of the database also in a session cookie at the beginning. kind regards, toni – Anatol Jul 10 '12 at 12:50
0

If your calculation is complicated enough to slow your server down, I don't think your clients would want to caclulate them in javascript either. If I read between the lines I don't think this is such a big calculation so why not go the safe (A) route, and let the server do this?

This way, your clients can't mess with the calculation: they can send to the database whatever they want (hey, it's a form), but in the end YOU do the calculation.

Don't optimize if you don't need to :)

Rudi Visser
  • 21,350
  • 5
  • 71
  • 97
Nanne
  • 64,065
  • 16
  • 119
  • 163
  • right. I will go this way. I struggled with the mysql thing. But will save the value as written one comment before at script start in a session cookie and only query the db when needed. – Anatol Jul 10 '12 at 12:52