开发者

Submitting a form via Ajax/jQuery

I have built a simple login form via ajax (jquery), but the submitted values (the users email address for login purpose, not the password) are not stored. So the second time the user tries to login he has to write his full email address instead of using the stored email address.

Is this normal with ajax form submission and (more important) is there a ajax/jquery solution, so that the browser "remembers" the submitted value?

if($(this).attr('href')=="#login")
{
    $.ajax({
        type: "POST",
        url: "http://www.xyz.com/register",
        data:({
            email : $('#email').val(),
            password: $('#password').val()
        }),
        success: function(result)
        {
            if(result=='ok')
            {
                window.location = 'http://www.xyz.com/123';
            }
            else
            {
          开发者_运维问答      $('#result').empty().addClass('error')
                    .append('Something is wrong.');
            }
        }
    });
    return false;
}


Are you performing the AJAX request directly in response from some UI event? What I can assume basing on your code is that it happens when user clicks some kind of 'Login' link. The login form itself isn't therefore submitted like it would normally be with no AJAX involved. This is most likely what prevents browsers from registering the form as being filled & sent, and offering to remember contents of its fields.

I suggest you to intercept the submit() event of your form and do the AJAX query in it:

$("#loginForm").submit(function(event)
{
    event.preventDefault();
    $.ajax({
        type: "POST",
        url: "http://www.xyz.com/register",
        data:({
            email : $('#email').val(),
            password: $('#password').val()
        }),
        success: function(result)
        {
            if(result=='ok')
            {
                window.location = 'http://www.xyz.com/123';
            }
            else
            {
                $('#result').empty().addClass('error')
                    .append('Something is wrong.');
            }
        }
    });
    return false;
}

The preventDefault() call will override the default submitting behavior of the form and allow you to perform AJAX request instead. Now you can either just add a normal Login button (HTML 'input' tag of type 'submit') or manually submit the form in response for clicking the link you already have:

$("a[href='#login']").click(function () { $("#loginForm").submit(); });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜