简体   繁体   中英

jquery ajax just isn't working

Ok, thats basically what i got. I also tried static values.

$('#submitForm').submit(function() {
    $.ajax({
        type: $(this).attr('method'),
        url: $(this).attr('action'),
        data: $(this).serialize(),
        success: function (data) {
            console.log(data);
        },
        error: function (data) {
            console.log(data);
        }
    });
});

What i get as response is this:

Object {readyState: 0, responseText: "", status: 0, statusText = "error"} 

The php script (just a simple echo) runs as normal after that ajax call. What am i doing wrong? My submit script doesn't look all that wrong to me and i'm not doing XSS. : - (

My HTML Form looks like this:

<form action="http://dev.xxxxxxx.de/users/register" method="post" accept-charset="utf-8" class="form-horizontal" id="submitForm">                <div class="control-group">
                <label class="control-label" for="inputUsername">Nickname</label>
                <div class="controls">
                    <input type="text" name="username" id="inputUsername" value="" placeholder="Nickname" />
                </div>
            </div>
            <div class="control-group">
                <label class="control-label" for="inputEmail">E-Mail</label>
                <div class="controls">
                    <input type="text" name="email" id="inputEmail" value="" placeholder="E-Mail" />
                </div>
            </div>
            <div class="control-group">
                <label class="control-label" for="inputPassword">Passwort</label>
                <div class="controls">
                    <input type="password" name="password" id="inputPassword" value="" placeholder="Passwort" />
                </div>
            </div>
            <div class="control-group">
                <div class="controls">
                    <input type="submit" class="btn" value="Account erstellen" />
                </div>
            </div>
        </form>

You need to tell the browser not to submit the form by default with:

e.preventDefault();

So:

$('#submitForm').submit(function(e) {
    e.preventDefault();
    $.ajax({
        type: this.method,
        url: this.action,
        data: $(this).serialize(),
        success: function (data) {
            console.log(data);
        },
        error: function (data) {
            console.log(data);
        }
    });
});

Otherwise, your form will submit according to the "action" attribute, before your AJAX returns.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM