简体   繁体   English

AJAX邮寄表格无效。 它绝对无能为力

[英]AJAX post form won't work. It does absolutely nothing

There was an error in my code and there was also a js file included inside my page which prevented anything from executing inside $(document).ready(function () { ... 我的代码中有一个错误,页面中还包含一个js文件,该文件阻止了$(document).ready(function(){

i'm trying to sumbit this login form: 我正在尝试汇总此登录表单:

<form class="form" id="AjaxForm">
        <input type="text" name="username" placeholder="Username">
        <input type="password" name="password" placeholder="Password">
        <button type="submit" id="login-button">Login</button>
</form>

Via ajax with this code: 通过带有此代码的ajax:

var request;
$("#AjaxForm").submit(function(event){

    // Abort any pending request
    if (request) {
        request.abort();
    }
    // setup some local variables
    var $form = $(this);

    // Let's select and cache all the fields
    var $inputs = $form.find("input, select, button, textarea");

    // Serialize the data in the form
    var serializedData = $form.serialize();

    // Let's disable the inputs for the duration of the Ajax request.
    // Note: we disable elements AFTER the form data has been serialized.
    // Disabled form elements will not be serialized.
    $inputs.prop("disabled", true);

    // Fire off the request to /form.php
    request = $.ajax({
        url: "login.php",
        type: "post",
        data: serializedData
    });

    // Callback handler that will be called on success
    request.done(function (response, textStatus, jqXHR){
        // Log a message to the console
        console.log("Hooray, it worked!");
    });

    // Callback handler that will be called on failure
    request.fail(function (jqXHR, textStatus, errorThrown){
        // Log the error to the console
        console.error(
            "The following error occurred: "+
            textStatus, errorThrown
        );
    });

    // Callback handler that will be called regardless
    // if the request failed or succeeded
    request.always(function () {
        // Reenable the inputs
        $inputs.prop("disabled", false);
    });

    // Prevent default posting of form
    event.preventDefault();
  });

Which i found here: jQuery Ajax POST example with PHP 我在这里找到的内容: PHP的jQuery Ajax POST示例

I'm trying to post it to login.php which checks if it is a valid username and password. 我正在尝试将其发布到login.php,它检查它是否是有效的用户名和密码。 But when i press the Login button it just puts the username and the password in the url and does nothing. 但是,当我按下“登录”按钮时,它只是将用户名和密码放在url中,却什么也不做。 And when i add action="login.php" method="POST" It submits the form but not via ajax because when i comment the ajax code out it still submits. 当我添加action =“ login.php” method =“ POST”时,它提交表单但不通过ajax提交,因为当我注释掉ajax代码时,它仍然提交。 I'm trying to prevent that. 我正在努力防止这种情况。 Any insights on my problem? 对我的问题有任何见解吗?

EDIT: lives here for now: http://5f6738d9.ngrok.io/test/public/index.html username and password are test 编辑:现在住在这里:http: //5f6738d9.ngrok.io/test/public/index.html用户名和密码已测试

Your submit button is a standard submit type button which means that your form will be submitted normally. 您的提交按钮是标准的提交类型按钮,这意味着您的表单将正常提交。 Based on your HTML code it will just submit the form to the same URL. 根据您的HTML代码,它将仅将表单提交到相同的URL。 The JS code will not have time to execute. JS代码将没有时间执行。 All you need to do is cancel de default HTML form submit by adding 您需要做的就是通过添加取消默认的HTML表单提交

event.preventDefault();

You need to add this first thing in your submit listener. 您需要在提交侦听器中添加第一件事。 So your JS code will start like this 因此,您的JS代码将像这样开始

$("#AjaxForm").submit(function(event){
    event.preventDefault();
    // Abort any pending request
    if (request) {
        request.abort();
    }
    //....

Try using the following code: 尝试使用以下代码:

$(document).ready(function(){
    $('#AjaxForm').on('submit', function(event){
        event.preventDefault();

        if(request){
            request.abort();
            request = false;
        }

        var $form = $(this);
        var serializedData = $form.serialize();
        var $inputs = $form.find("input, select, button, textarea");
        $inputs.prop("disabled", true);

        var request = $.ajax({
            url: 'login.php',
            type: 'POST',
            data: serializedData,
            success: function (data, textStatus, jqXHR) {
                // login was successful so maybe refresh the page
                window.location.reload();
            },
            error: function (jqXHR, textStatus, errorThrown) {
                // display form errors received from server
            },
            complete: function (jqXHR, textStatus) {
                request = false;
            }
        });
    });
});

Check that the event is bound within a $(document).on('ready' ... otherwise the event won't fire and the form will just submit normally or not via AJAX. 检查事件是否绑定在$(document).on('ready' ...否则事件将不会触发,并且表单将仅通过AJAX正常提交或不提交。

Your code should look like: 您的代码应如下所示:

$(document).on('ready', function () {
    var request;
    $("#AjaxForm").submit(function(event){

    // Abort any pending request
    if (request) {
        request.abort();
    }
    // setup some local variables
    var $form = $(this);

    // Let's select and cache all the fields
    var $inputs = $form.find("input, select, button, textarea");

    // Serialize the data in the form
    var serializedData = $form.serialize();

    // Let's disable the inputs for the duration of the Ajax request.
    // Note: we disable elements AFTER the form data has been serialized.
    // Disabled form elements will not be serialized.
    $inputs.prop("disabled", true);

    // Fire off the request to /form.php
    request = $.ajax({
        url: "login.php",
        type: "post",
        data: serializedData
    });

    // Callback handler that will be called on success
    request.done(function (response, textStatus, jqXHR){
        // Log a message to the console
        console.log("Hooray, it worked!");
    });

    // Callback handler that will be called on failure
    request.fail(function (jqXHR, textStatus, errorThrown){
        // Log the error to the console
        console.error(
            "The following error occurred: "+
            textStatus, errorThrown
        );
    });

    // Callback handler that will be called regardless
    // if the request failed or succeeded
    request.always(function () {
        // Reenable the inputs
        $inputs.prop("disabled", false);
    });

    // Prevent default posting of form
    event.preventDefault();
  });
});

Note that these callback events are actually deprecated as of jQuery 1.8. 请注意,实际上从jQuery 1.8开始不推荐使用这些回调事件。

You will also need to ensure that your POST and action attributes are set on the form in all cases. 在所有情况下,您还需要确保在表单上设置了POSTaction属性。

Personally I would use this instead: 我个人将使用它代替:

$(document).ready(function(){
    $("#AjaxForm").on("submit",function(e){
        e.preventDefault();

        var $form = $(this);
        var $cacheData = $form.find("input, submit");
        var serializedData = $form.serialize();

        $.ajax({
            url: $form.attr("action"),
            type: $form.attr("method"),
            data: serializedData,
            xhrFields: {
                onprogress: function(e){
                    $cacheData.prop("disabled", true);
                    console.log(e.loaded / e.total*100 + "%");
                }
            },
            done: function(text){
                if(text == "Succes!"){
                    alert(text);
                } else {
                    alert(text);
                }
            },
            fail: function(xhr, textStatus, errorThrown){
                alert(textStatus + " | " + errorThrown);
            },
            always: function(){
                $cacheData.prop("disabled", false);
            }
        });
    });
});

This allows you to do some usefull things: 这使您可以做一些有用的事情:

  1. You're able to monitor the progress in the console 您可以在控制台中监控进度
  2. Just because Ajax is succesfull, doesn't mean you can't have an error returned. 仅仅因为Ajax成功了,并不意味着您就不会返回错误。 For example: Wrong password. 例如:错误的密码。 So now you can simple echo errors back this script will show them. 因此,现在您可以简单地回显错误,此脚本将显示它们。 Echo "Succes!" 回声“成功!” when the login was fine. 登录正常时。

Keep in mind though that this script requires that you set the HTML attributes action and method in your form. 请记住,尽管此脚本要求您在表单中设置HTML属性actionmethod

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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