Judking
Judking

Reputation: 6371

A phenomenon comfuses me when posting form data via jquery.ajax

This is my form:

<form id="login_form">
    <table border="0">
        <tr>
            <td>username: </td>
            <td colspan="10">
                <input id="username" name="username" type="text" />
            </td>
        </tr>
        <tr>
            <td>password: </td>
            <td>
                <input id="passwd" name="passwd" type="password" />
            </td>
        </tr>
        <tr style="text-align:center">
            <td>
                <input id="login_submit" type="submit" title="submit" />
            </td>
            <td>
                <input type="reset" title="reset" />
            </td>
        </tr>
    </table>
</form>

My jquery code:

$(function(){
    jQuery("#login_submit").click(function() {
        jQuery.ajax({
            url:'./login/',
            type:'post',
            data:$("#login_form").serialize(),
            dataType:'html',
            async: false,
            success:function(backData)    {
                alert(data);
            },
            error:function(err){
                alert('error = ' + err);
            }
        });
    });
}); 

What I confuses about is that when I visit url: http://192.168.0.3/CarKeeperServer/user/login.jsp, click on the submit button(the page won't direct to a new page because there's no redirect code in jquery code snippet), and the url will change to http://192.168.0.3/CarKeeperServer/user/login.jsp?username=df&passwd=sd, which exposes my username and password just like in a GET method. Could anyone explain why this will happen and what the solution is? Thanks a lot!

Upvotes: 2

Views: 103

Answers (1)

Kevin Bowersox
Kevin Bowersox

Reputation: 94469

You need to prevent the form from submitting by calling preventDefault. The reason your seeing a get request fired is that you haven't prevented the form from submitting, which is submitting to the current page you are on.

By default a form uses the get method to send information to the server. See: http://www.w3.org/TR/html401/interact/forms.html#adef-action

Since the form does not specify a default action, it uses the current page as the action. This is not designed into the HTML specification, but is implemented by many browsers to maintain legacy applications. See: Is it a good practice to use an empty URL for a HTML form's action attribute? (action="")

$(function(){
    jQuery("#login_submit").click(function(e) {
        jQuery.ajax({
            url:'./login/',
            type:'post',
            data:$("#login_form").serialize(),
            dataType:'html',
            async: false,
            success:function(backData)    {
                alert(data);
            },
            error:function(err){
                alert('error = ' + err);
            }
        });
        e.preventDefault();
    });
}); 

Upvotes: 5

Related Questions