I see that validating forms using Ajax can be quite useful to avoid code duplication. And before implementing it I am interested if the are any disadvantages of this technique comparing to simple javascript validation. I see only couple of arguments, but I think they are quite weak to take them into account:
It's obvious that ajax will increase server load, but it's only 5-6 connections per form which should not be a performance bottleneck.
Also I see that js validation can work offline, but as we need to submit a form in the end it can't work without Internet connection anyway.
Speed is also not the issue as now broadband is available almost everywhere.
Are there any other arguments that I miss?
Ajax validation is great from a user experience point of view, because you get immediate feedback.
One thing to keep in mind is that even if you validate the form using ajax, you still need to re-validate the submitted values once they hit the server to prevent security exploits, since an attacker could just use something like curl to send arbitrary values.
To take the contrary position:
1) 5 or 6 requests is no big deal - but 5 or 6 times as many connections per-user per-form - that is. If you are talking about taking your server from 100k to 600k connections a day, better think about it.
3) Broadband is everywhere, but so are slow and unreliable wireless connections. Depending on how you implement it, the form could feel very clunky.
And you definitely do need to re-validate on the server - but that's what you are saying: reuse that logic that is on the server anyway, via ajax, instead of replicating it on the client with JS.
Just a side note: Some frameworks allow you to declare validation in one place and then generate the Javascript (non-ajax IIRC) and the server-side for you. I know JSF (Java Server Faces has this) and I think .net does also.
If all you're asking is
I am just asking if i will validate
a form with javascript instead of ajax
will I gain anything that I can't do with ajax
then no. In the end point - you get a gesture for the user on his bad input.
However, I will not so lightly disregard server load.
5 additional requests per form - to redo on the server checks that it needs to do on form submit - that's about doubling the server work on your forms.
Also - mind that AJAX is also javascript, so you're not completely rid of it.
And last - JavaScript with server roundtrip (and AJAX is a server roundtrip) will not be as immediate as simple JavaScript.
However - yes. it is code duplication. That is your trade of, and any decision you make is valid if your project can take it.
Edit: fixed a typo + move to community wiki
Related
I read here that the main reason for using client side validation is:
the user can correct every field before they submit the form
This (sort of) assumes Ajax, but if the client side validation consists purely of Javascript, is there really a point to it anymore? It's easy enough to point out specific mistakes and store form data on refresh from PHP / Django / node.js, so if the client side script isn't pointing out mistakes as the user is making them, does it really make sense both from a UI and developer perspective to take the time to write that bit of code?
Client side validation helps you prevent errors from entering into your server/database and adds a second layer of protection.
As far as Ajax is concerned, you will be sending your data from the client to the server one way or another so if you're using Ajax or not is irrelevant.
From a developer's perspective, even something as simple as checking all the fields for valid data types on form submit is worth the effort. This saves your server from having to process an invalid entry and shifts that load to the user's system. For large scale applications this dramatically increases performance.
From a UI perspective, I understand that incorporating error checking into the form makes it a little bit difficult, but in my opinion this is a minor inconvenience to save you much more hassle of having to clean your database in the long run.
Edit: As Ryan pointed out in his comment to the question, users definitely appreciate feedback without having to wait for it
I have been developing a PHP application for quite a while. The (basic) idea is as follows; users can build web-pages using blocks. These blocks can contain images, text etc. Each of these blocks have their own options. These blocks are defined in Domain Driven Design through PHP.
I've build the application to use a php-based Controller that handles the requests from a jQuery/Javascript front. Each time the user edits an option its send to this Controller which unserialises a collection of blocks (php-objects) from Redis and/or the php-session and sets the the attributes of the blocks that are edited or adds/removes one of the blocks. This is to enforce the Domain logic.
Which was fine will developing for myself. I never kept race conditions and such in mind. While moving forward with the product I notice that people lose data. I'll explain what happens;
User edits an option of a block
press save
A request is made to the controller which,
unserialises the collection and
sets the blocks based on their uuid
puts the blocks back in the collection and
serialises the collection again.
There are scenario's where 2 concurrent request might be created which will override the edits of 1 of both requests.
I know I need to rewrite this part of the application. The question is what is the best approach. I could;
Implement some javascript library which will take me a lot of work because it would require me to rewrite that entire part of the application. Also I do not have a lot of experience implementing javascript based solutions. But I do not might stepping into something new. I do want to javascript testing to prevent future problems from occurring and enable cross-browser testing
Apply Redis / Session locking to only enable the controller to process a single request and prevent concurrent requests from overwriting the data set in the previous request. This will lower the chance of concurrent request and data loss, but not fully. People with real slow internet connection might get their connections losing when they might produce a lot of concurrent requests.
I'm curious what other approaches I might be missing, or if one of the two I mentioned above will suffice.
As far as I understand your problem, what you may want to implement is optimistic locking.
A simple way to implement it, is to version your aggregate.
Every time someone edits your object, increment its version.
When you POST your edited blocks, you send back the version on which you are trying to apply your changes.
then, when getting back your object from your persistence storage, you compare the version and ensure you are actually working on an up-to-date object.
If it is, save it, if it is not, reject the modification, notify the user, and reload the object, and take the appropriate action (it depends on your needs).
I use some jquery and JS functions to validate forms and to check for example if that field is empty or password is less than 6 characters, and stuff like that, and I noticed that if someone disabled JS, then these functions would be useless, and no more protection of forms, which can be better made using PHP, so should I avoid them now because this could cause an insult to my website ?
JavaScript is very useful for improving user-interaction, along with reducing the number of requests made on the server; but, as you've pointed out, it can be disabled. To answer your question: No, I wouldn't recommend avoiding the use of JavaScript, but the key is not to rely on it for critical actions, such as validation. You'll want to implement the validation on both the client (JavaScript) and server (PHP) sides. This will ensure that there is no way for the user to completely disable the validation.
In short:
JavaScript = Good
JavaScript Validation = Nice for the user, but not reliable
Server Side Validation = Essential
Side note:
With regards to relying on JavaScript for the overall user interaction, as other answers have suggested, use JavaScript to enhance the overall experience, but don't rely on the user having it turned on. I would recommend a bit of bed time reading of Progressive Enhancement, it's the approach of making something better, with being reliant on it, and can be applied to more than just JavaScript (CSS3 etc).
You should use javascript and jQuery to enhance the functionality of your site. If someone has javascript turned off you should ensure that the site still works, and they can access all areas - even though there may be some things they cannot see, such as transitions and effects.
With regard to validation, you should ALWAYS validate server side. Client side validation is optional, but a very nice feature to improve the user experience for your visitors.
I don't mean this as a complaint, more of an observation.
Web developers often grab Javascript libraries as the latest shiny toys with no thought for the consequences. As a Data Governance person, I'm regularly the bringer of bad news, when we do audits on the data collected, and find users who get past the Javascript validation.
"Go back and start again".
Javascript libraries are great for the presentation of data, but should and must not be relied on for data validation and the integrity of user profiles.
A validation should always happen at
Client Side - using javascript to enhance the user experience.
Server Side - using the preferred server side programming language for security reasons
Service Side - if you are following SOA / Web API as part of defensive programming practice. This can also be at the DB level along with Service layer.
You should not avoid using JS and jQuery in your website, but you should avoid using them for validation purposes or business-logic purposes. These should be done in the back-end of the website, not in the UI level.
You shouldn't really avoid them. What you should do is to implement both client and server validation. Don't rely just on client validation, for the reasons you just mentioned. You should always validate the data when it arrives to server.
Adding client-side validation gives your pages dynamic look and feel. A user does not have to wait for the form to go to server and in case of an error to return back. It is automatically verified without postback.
As I said above, don't rely upon client side validation. Always implement server-side validation also.
Remember my friend, Java script is client side scripting. its purpose to validate form at client side itself so we can avoid overhead...You must use java script at client side. because PHp is server side language. It will take time to reply.
Ha, Server Side validations are equally important. if you want to do that, then you can use server side language. You can check comment below to my post by halfer. Server side validations are important for security and many more purposes.
That is different thing that somebody disabled js. You can check for the same and give proper message to enable.
I'm modifying an existing web application that features the ability to administrate users who are able to log into the system. When modifying a user's details via a dialog, update data is sent to the server via AJAX. A few lines of javascript to then update the current page to reflect these changes is returned with the intention of being executed. This strikes me as poor form - isn't executing remotely acquired JS dangerous?
If I were to modify this, I would have the AJAX call that sends the updated information then call another function that gets the latest data from the server via AJAX (or just refresh the page, if I am feeling lazy). Is there any advantage (mainly security, but from an architectural perspective as well) to making this change, or am I being anal?
Assuming we're talking about eval used on non-json.
People will tell you all sorts of things, most of it has some basis in reality. I'd say one reason that is really understandable: it will make the code a nightmare to maintain and it will be very hard to trace bugs.
There are security concerns, a lot of people like to jump on the "javascript is the clients problem" bandwagon. I say if it comes from your site, it's your problem too.
In the end, there is no good reason I can think of to eval javascript from the server. Pass data from the server, and write the javascript on the client-side to react to that data.
All JS executed by the browser is remotely acquired.
The server that returned the JS/JSON via AJAX is the same server that returned the HTML that did the AJAX call in the first place.
It if's possible to do something bad, it can be done whether you eval the result of the AJAX call or not.
Personally, I don't see the issue. Sure, people say things such as "It allows code execution client-side" however if the potential attacker is able to affect that, then that's your problem - not the ability to modify the code.
Seriously, I think you have far more pressing concerns than that. I'd personally spend that 10 minutes or so reviewing your code and looking for flaws instead of working on an alternative to eval(). I think it'll improve your security a fair bit more.
Mike Samuel mentions MITM. I don't see why. If you're susceptible to a MITM attack then chances are that code can be injected straight into the initial HTML page (again, sure, slightly higher risk but is it really worth worrying about? Your choice.)
If a trusted developer wrote all of it and you protect it the way you do the rest of your HTML page, then no.
But even if it is JavaScript written by trusted developers, if it is served over HTTP, then an attacker can modify it in-flight because HTTP over free wireless is often susceptible to MITM.
This can be used to effectively install a keylogger in the current browser window to steal user passwords, redirect them to phishing pages, etc.
The attack might work like this:
Web page does a GET to http://example.com/foo.js.
Attacker modifies foo.js mid-flight to add JavaScript that does window.addEventListener("keypress", /* a keylogger that sends all keys to evil.com cross domain by image loading tricks */)
Browser loads modified JavaScript.
User enters a password in an <input type=password>.
Evil wins.
Since HTTPS (assuming no mixed content) is not susceptible to MITM, it is not vulnerable to this attack.
You probably don't want to just call another function after you send the data update because you could then display information that isn't true if an update fails. At least with the current model, your service can tailor the javascript based on whether or not the update was successful. You may want to consider having the service just return a true/false and have the call back function handle the updating of the UI.
Sort answer: Yes
Long answer: You should just send data for both security reasons and to keep your implementations separate.
Improperly sanitized user-submitted content or advertisements could inject code and get it run. Granted, this would have to be a targeted attack, but hey maybe you're working for a startup that's going to be the next Google or a forum system that's going to be the next vBulliten. Even if you have 10 users, security holes are still holes and are still bad for you and your users. Also, bad security advice left lying around SO will lead others to make bad decisions.
Do you really want to have to make sure the code you generate on the fly and send to the client is correct in all possible cases? What if someone else works on just one half of the system? Are they going to know every variable name to avoid stomping on? Just sending data is the best way to keep a 'small' change in your client/server communication from breaking everything in ways that aren't obvious and will take forever to debug.
Web-Applications these days make extensive use of Javascript, for example various Google Products like Gmail and Calendar.
I'm struggling to how NOT having duplicated logic server and client side.
When requesting a page or state of the application, i would prefer to send the complete UI, meaning: not just some javascript, which in turn makes a dozen ajax requests and builds the user interface.
But here lies the problem, the logic deciding what to show or not has to be written once in the server-side and once in the client-side language.
Then i was wondering if it was somehow possible to process your javascript logic server-side and send the whole to the client, who in turn can continue using the application with all the advantages of a responsive ui, but without disadvantage of the initial loading/building of the user interface due dependency of background ajax requests.
I hope the explanation of my problem is a bit clear, because i'm not the most fluent English writer. If you understand what i mean and if you can describe the problem a little better, please do... thanks!
So my question is:
Is something like this possible and or realistic?
What is your opinion on how to tackle this problem?
;-)
When we started our web app, we had the same kind of questions.
It may help you to know how we ended:
The backend (business logic, security) is totally separated from the frontend (gui)
frontend and backend communicate through JSON services exclusively
the JSON is rendered client-side with the PURE templating library
and the backend is Erlang (anything streaming JSON would be ok too, but we liked its power)
And for your question, you have to consider the browser as totally unsafe.
All the security logic must come from the backend.
Hiding or showing some parts of the screen client side is ok, but for sure the backend decides which data is sent to the browser.
Seems you describe Jaxer.You can write everything in JS. Also, there is GWT that allows to write whole thing on Java
Then i was wondering if it was somehow
possible to process your javascript
logic server-side and send the whole
to the client, who in turn can
continue using the application with
all the advantages of a responsive ui,
but without disadvantage of the
initial loading/building of the user
interface due dependency of background
ajax requests.
Maybe the apps you're looking at just use Ajax poorly.
The only content you can pre-process on the server is the content you already know the user wants. For example, in an email app, you could send them a complete view of their inbox, pre-processed on the server and fetched with a single request, as soon as they log in. But you might use AJAX to fetch a particular message once they click on it. Sending them all the messages up front would be too slow.
Used correctly, AJAX should make your pages faster, because it can request tiny updates or changes of content without reloading the whole page.
But here lies the problem, the logic
deciding what to show or not has to be
written once in the server-side and
once in the client-side language.
Not necessarily. For example, in PHP, you might write a function like displayWidgetInfo(). You could use that function to send the initial widget information at page load. If the user clicks the widget to change something, send an AJAX request to a PHP script that also uses displayWidgetInfo() to send back new results. Almost all your logic stays in that single function.
Your instincts are correct: it's bad to duplicate code, and it's bad to make too many requests for one page. But I think you can fix those problems with some refactoring.
I understand what you're saying.
But I don't think you should be having much 'logic' about what to build, on the client side. If you did want to go with a model like you're proposing (not my cup of tea, but why not), I don't see why you'd end up with much duplicated.
Where you would normally show a table or div, you would just output JavaScript, that would build the relevant components on the client side.
I would consider it just as another 'View' into your data/business logic model.
Have you go a small example of a problem you're coming up against?
I understand your question in this way:
Suppose we have an html form on web-page. There is a field for name and surname. We have to check it for validity both on client-side (with JS) and Sever-side (on php script while processing form inputs). So here is the duplication - regex check on both sides. So what is the way to prevent it and combing these logics?