views:

59

answers:

2

After learning about jQuery and the whole AJAX thing, I got very excited. I decided to completely replace my forms with just input fields. And the data is sent to the server when the '<'input type="button" /'>' clicked.

// JavaScript
function submit() {
removeInfo();

btn = $('#button');

$('#button').replaceWith('<img id="theimage" src="/images/ajax-loader.gif" />');

$.post('/jlogin',
        {
            username: $('#username').val(),
            password: $('#password').val(),
            captcha: $('#captcha').val()
        },
        function (data) {
            if (data.status == 'SUCCESS') {
                window.location = '/successfullogin';
            }
            else {
                $(data.errorInput).addClass('inputerror');
                $(data.errorInput).focus();
                $('#spanFailed').text(data.info);
                appear('#divFailed');
                if (data.errorInput == '#captcha') {
                    captchaimage.src = '/captcha?i=2' + Math.floor(Math.random() * 11);
                }
                $('#theimage').replaceWith(btn);
            }                
        },
        'json'
);
}


<!-- HTML -->
<div id="divFailed" class="error" style="display:none; width:250px; height:25px;">
            <span id="spanFailed" class="spanerror">

            </span>
            <br />
        </div>    

        <br /> 


        Username:

        <input type="text" id="username"  />

        <!-- and other inputs here -->

        <input type="button" id="button" onclick="submit()" value="Login" >

So the problem is that if the user has no JavaScript enabled, s/he won't be able to use my web application. Also it's impossible to let browsers remember passwords.

I heard about serializing forms with JavaScript. But how would I be able to use these fancy red alerts when using forms without JavaScript?

So basically I want to have the same functionality but with forms.

+1  A: 

Good question and you are talking about 'progressive enhancement'.

Basically the form should first and foremost work with js disabled. If the client has js enabled then you can hookup some jQuery to hijack the form submission, by attaching an event to the submit button click event or form submit event and send the data using ajax.

Typically this looks like

$('#someSubmitButton').click( function(ev){

   //prevent default form postback

   ev.preventDefault();

   var data = $(this.form).serialize();

   $.post( url, data, callbackFunction);

});

Your second question - Scott Gu has a good walkthrough taking you through one way to do both server & client side validation to produce the same result.

redsquare
+1  A: 

I would not remove the "form" like what you did in your code - but instead supplement it with jQuery/AJAX/etc. So, in the case when javascript is disabled, your login functionality will still work.

<div id="LoginArea">
    <div class="message"><%:Html.ValidationSummary(true)%></div>
    <% using (Html.BeginForm("/MyController/MyLogin", FormMethod.Post, 
        new { id = "LoginForm", name = "LoginForm" })) { %>
    <input type="text" id="username"  />
    <!-- and other inputs here -->
    <input type="submit" id="button" value="Login" >
    <%}%>
</div>

Then create a submit interceptor with jQuery:

<script type="text/javascript">
$(document).ready(function () {
    $("#LoginForm").submit(function () {
        var f = $("#LoginForm");
        var action = f.attr("action");
        var serializedForm = f.serialize();
        $.ajax({
            type: 'POST',
            url: action,
            data: serializedForm,
            success: function (data, textStatus, request) {
                if (data.status == 'SUCCESS') {
                    window.location = '/successfullogin';
                }
                else {                   
                    $("#LoginArea").html(data);
                    $("#LoginArea").show(speed);                        
                }
            }
        });
        return false;
    });
});
</script>

Then do your error handling server side at the minimum (so if javascript is disable, your validation will still in place) and then you can add the corresponding client side if you want.

Johannes Setiabudi
Thanks! I'll do some changes in my code.
Alex