AJAX validations in struts 2 - javascript

Can we do client side validation using AJAX in struts 2 application ?
If yes, then please let me know the procedure.

Answer is right here.
http://struts.apache.org/2.x/docs/ajax-validation.html
even provides prototype example instead of dojo

As Sergio said, you could use this, for example, in a registration form where you have fields like:
Username
E-mail
Password
Repeat Password
You can set up some javascript to validate the form before the user submits it, or better yet, don't enable the submit form until all required fields are complete, avoiding user frustration (you tell him specifically where the error is and how to correct it) and adding another layer of validation to it.
In this case you can pre-validate Username and E-mail against the server to see they are not taken yet. You can do something like this (in jQuery, from memory):
$("#email").change(function(e) {
var $elem = $(this);
var val = $elem.val();
if (!val) {
myMarkField($elem, "not-valid");
myValidateForm("myForm");
} else if (!/^[a-z0-9_+.-]+\#([a-z0-9-]+\.)+[a-z0-9]{2,7}$/i.test(val)) {
myMarkField($elem, "not-valid");
myValidateForm("myForm");
} else {
$.getJSON("isEmailAvailable.php", {email:val}, function(result){
if (result.available) {
myMarkField($elem, "valid");
myValidateForm("myForm");
} else {
myMarkField($elem, "not-valid");
myValidateForm("myForm");
}
});
}
});
Where isEmailAvailable.php should return something like { available: true }

AJAX is the mechanism by which you could invoke the server-side validation. The "J" in AJAX stands for Javascript.
You would typically make use of AJAX (and hence Javascript) to invoke some sort server-side validation that would be inappropriate for client-side validation. For example, the validation of a zip code against a table of acceptable values.

How would you do this? You use JS for client-side programming (including validation), it has nothing to do with the server side.
Additionally: server-side-validation via the client-side JS would be a bad idea, as all your validation code would be exposed to the user.

If your going to do server-side input validation then what do you need to use JavaScript for?
I'll make the assumption that you are using PHP on the server-side in which case you'll want to validate it there instead of making another unnesicary request.
If you want to use AJAX to do some server-side validation (and you'r using JQuery) this should at least get you started:
function validate(fieldName)
{
$.get('/validation.php',
{'value' : fieldName.value, 'name' : fieldName.name},
function(data, textStatus)
{
if(data)
{
fieldName.style.class = 'validFormInput';
}
else
{
fieldName.style.class = 'invalidFormInput';
}
})
}
I'm no JS/JQuery expert and I didn't test this so it's just to get you started.

I think you need to read a bit about AJAX.
I recommend this link: http://rajshekhar.net/blog/archives/85-Rasmus-30-second-AJAX-Tutorial.html
I think it's simple and easy to understand.
Basically you have server and client side code. JavaScript (client side) can invoke a URL using Ajax(Asynchronous JavaScript And XML) witch is very similar to invoke any other URL using a browser. The main difference is that there is no page reload.
Your JavaScript will need to be waiting for the reply in order to handle it (in your example show or hide an error message).
Basically it allows you to execute some code at the server an update your page without a page refresh.

In short, the AJAX application architecture enables the client (i.e. a piece of JavaScript running in a web browser) to actively ask for information from a server. Most often, the JavaScript client will use the received information to update small portions of the browser's document using the DOM.
Also, the JavaScript client code can do some obvious validation of e.g. a form to be sent to a server (as shown so nicely by Danita's answer).
The server can be anything. It may just return a plain xhtml file, or may respond to the request by calling a complex PHP script that generates a response. Heck, it may even be a dedicated mobile device entirely implemented in bare C. As long as it implements the http protocol the client's request was transmitted in. This might be JavaScript. Improbable but true.
So Yes: it can be done using 'server-side' JavaScript, if you have a server running JavaScript. But No: that's not probable.
And Yes: you apparently need to read upon AJAX. (I'm not a webdesigner, and even I seem to know more than you ;) Don't leave it that way!)

Related

Comparison of simple User Regeistration by PHP and Javascript

A simple user registration may be completed by PHP (framework: Codeigniter,etc..) and Javascript.Following is simple flow:
PHP
A registration view with form input(user_name,e-mail,password)
post the data to an controller to validation
-Pass, redirect to a completion view
-Failed, go back to the registration view with some alert strings.
Javascript
A registration html with input text(user_name,e-mail,password)
Validation could be done by Javascript directly before submit; Alert strings could be
generated by Javscript. Even submission could be done by ajax. Then redirect to the
completion page.
I found myself code more javascript less PHP. Even the user registration could be done without the "form" tag,right? I am afraid of some parts I had miss or ignore.
Could someone gives me an simple comparison of good/bad parts about these two methods?
User registration details have to be stored on the server. You can use any language you like there, JavaScript (node.js is the current preferred way to achieve that), Perl (PSGI/Plack), Python (WGSI), C# (ASP.NET), PHP (mod_php), whatever. If you did it entirely with client side JavaScript, then the registration would exist only for a particular browser (which makes it rather pointless for almost anything on the WWW).
You can do a lot of things with client side JavaScript.
You can test if the data enter by the user conforms to the requirements you've set (such as "usernames contain only ascii alphanumeric characters").
You can't stop data that doesn't conform to those requirements being submitted to your server though - everything outside your server is beyond your control. Users can edit your pages in their browser as much as they wish. Client side validation is a convenience to the user (giving feedback without a server round trip and page reload), nothing more.
You can use Ajax instead of an HTML form … but there is no reason to do that. It just adds an unnecessary dependancy on JavaScript. That doesn't mean Ajax can't be useful, you could use it to ask the server if a username was already taken while the user is filling out the rest of the form.

How to prevent the clientside user from changing arguments in an onClick function?

I just realized while testing an onClick function with firebug that it would be really easy for a user to change the value of the arguments being passed. This could mess thins up.
Is there any easy way to prevent this, especially when arguments need to be passed?
It is impossible. The code is executing on the user's computer. They are in control.
If they edit it and "mess it up", then that is on their head.
If they edit it and it submits an HTTP request to your server, and your server allows (for instance) that request to delete data belonging to another user then the problem is that your server didn't check that the user submitting the request had permission to delete that data before following through.
You cannot trust anything sent from the client. The user might hand-edit the URL arguments, or a script kiddie could send you a request not even using a browser at all. You must validate everything server-side.
No, this simply can't be done.
Once the script is loaded to the client's machine. He can use/modify it, as he wants.
I'd recommend validating the arguments against expected set of values, and/or business rules wherever the results are being processed (client/server). Ideally validation checks happen on the server where the user has no control. Validation on the client side could even be modified to allow invalid data entry.
There is no way to completely control it - only validate it based on criteria.
You can't prevent this action because JavaScript is a client side . Also you can never trust the client .
You should make a validation for any request at server side to protect your data against client misuse .
you can somehow make it hidden from client eyes
by using .delegate()
EX.
$("table").delegate( "td","click", function() {<br>
// write here your function<br>
});
The client can execute this script but it isn't direct in front of his eyes ..

Node.js server-side form validation with client-side response

Express-form is a quite powerful validation plugin for node.js/express. However, in the examples and documentation, all the responses are server-side (console.log), which is enough for development, but not quite practical to tell the user what's wrong.
At the moment, I can imagine two different solutions:
Submit the form and redirect back / render the form again with req.body and validation messages attached to add 'error'-classes to wrong fields.
Submit the form using AJAX.
I would prefer option 2, as I don't want to query the database again when rendering 'new'. But I have no idea how to pass the validation results back to the client and add 'error'-classes to input fields.
Any ideas?
I try to validate user input via javascript in the first instance in the browser, and then validate on the server outputting errors in the rendered form (a la rails). Right now I'm using my set of custom validators so I can't point you in the right direction with express-form.
Along with my custom regexes I, sometimes, use the validator npm package, you can also use the validator validations in the browser using plain DOM or some framework.
edit:
working with AJAX validations is quite easy, you receive an object in your request (if you use express.bodyParser() middleware), validate the parameters, if there are some errors you can point at it in your response ex.
{
"errors": {
"foo": "must be a number"
}
}
and:
for (i in answer.errors) {
var target = document.getElementById(i);
target.class = "error";
// here you can also handle the error description
}
If you are using a framework on the browser side, there are plugins or I'm sure it's simple to write one.

Perl - Submit Javascript action to host

I am building a Spider in Perl and have a problem:
The Site I want to spider uses a JavaScript for Age-Verification and I don't know how to get past this in Perl...?
The Script looks like this:
<script type = "text/javascript">
function set_age_verified(){
new Request({
method: "post",
url: "/user/set_age_verified"
}).send();
$('age_verification').setStyles({visibility: 'hidden', display: 'none'});
$('page_after_verification').setStyles({visibility: 'visible', display: 'block'});
return false;
}
</script>
And here the OnClick Event :
<img src="http://example.com/age-verification-enter.gif" alt="ENTER">
The function has two effects. One is to POST a request to the URL "/user/set_age_verified" and the other is to alter the display visibility of some HTML.
Your spider can easily ignore the second effect, but presumably the first effect, by going to the server, sets some cookie or server variable which the server will require.
You do not have to actually run the javascript, so long as the server sees the same POST data.
The answer is for your Perl script to detect pages which have this javascript, and to call a Perl function to POST the data to the age verification URL.
Any cookie or similar which is returned will have to be recorded by you - your HTTP library may take care of this for you though.
What Perl modules are you using? WWW::Mechanize has an AJAX plugin, although it hasn't been updated in a while. I guess you could also look at something like WWW::Selenium.
But I bet that AJAX request is going to inject some HTML that requires the user to input some data, then submit a form. Pretty tricky to cover all bases for that general case...
Take a look at the WWW::Mechanize::Firefox module. It allows you handle some JavaScript.
Also, in Firefox HTTPHeaders is your best friend.
Turn it on, manually click what ever you need to in order for the Javascript to run and submit to the server, then go back to the HTTPHeaders window. It will show you exactly what that Javascript event sent to the server (GET or POST + the data, even if it is HTTPS) - as well as the server response.

gwt javascript checking php

i am using gwt.
i need to check some input data.
all checking functions are located in PHP server check.php
i am not using javascript checking executed from locally.
all i am doing is to send user input to server by ajax and validate in that place
and error message comes from server to client's gwt widget.
is it best approach??
i can do all checking from locally.but not doing.because server side is importent.
all checks must be resides in server so i am doing all checking from server.
if i do check locally and serverside two times ,then will it be best approach??
What you'll want to do is:
Use this account the next time you come back, or any of the others you've created, instead of creating an account each time you come to the site. Avoid this mess.
Create a .php page that accepts JSON-encoded data that you'd like to verify, and respond with some text like "OK" if it's valid. (I'm no PHP expert, but I'm sure there are plenty of them here)
Use GWT's RequestBuilder to send this data to the .php page, and call the RequestCallback's Response's getText() method. Check if the text is "OK" -- if so, the result is valid!
If you need more detail on any of the specifics, just let me know and I'll edit to clear things up.
Generally I agree with Jason (especially the with the first point :D).
I'd like to add that you should do validation on the client side first. Why? Because it allows you to weed out some obviously wrong inputs => less load on the server. But never accept the values from the client, just because your JS code said so - the general rule is to never trust the client side (because, well, it's the client side and the client can change the way your code works).
So in summary, I usually take these steps in my apps, they offer security and lower the load on your server, but may require a bit more work to write and maintain (especially if your client side and server side use different languages):
Validate input client side. If it doesn't pass, don't bother sending it to the server, just show an appropriate message.
If it does pass, send it to the server, but you must rerun the validation on the server side too.
If the server side validations report an error, send it back in some form (JSON with the error message and/or error code, set a HTTP response code, etc).

Categories

Resources