jQuery:$ .ajax()重定向到其URL表单操作参数,而不是对表单操作执行AJAX请求

时间:2022-11-23 17:51:30

I will show my code first before explaining my problem.

在解释我的问题之前,我会先显示我的代码。

Here is my form:

这是我的表格:

<form id="update-sale-form" method="POST" action="actions/updatesale.php">
<table id="update-sale-table" class="table borderless">
    <tr>
        <td><label>Item Code</label></td>
        <td id="item-code"></td>
    </tr>
    <tr>
        <td><label>On Sale?</label></td>
        <td>
            <input type="hidden" id="itemcode" name="item-code" value="" />
            <select id="is-sale" class="form-control" name="is-on-sale" onchange="checkSale(this.value)">
                <option value="0">No</option>
                <option value="1">Yes</option>
            </select>
        </td>
    </tr>
    <tr>
        <td><label>Percentage</label></td>
        <td>
            <div class="input-group">
                <input type="text" id="sale-percentage" class="form-control input-sm" name="sale-percentage" onkeypress="return isNumberKey(event)" maxlength="2"/>
                <span class="input-group-addon">%</span>
            </div>
        </td>
    </tr>
</table>
<div class="response"></div>
</form>
<script type="text/javascript">
function disableSalePercentage(){
    $('#sale-percentage').prop('disabled', true);
    $('#sale-percentage').val('0');
}

function isNumberKey(evt){
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;
    return true;
}

function checkSale(value){
    if(value=='0'){
        disableSalePercentage();
    } else {
        $('#sale-percentage').prop('disabled', false);
        $('#sale-percentage').val('');
    }
}

Here is my PHP file that handles the request.

这是我处理请求的PHP文件。

<?php
session_start();
require '../config/consettings.php';

$itemCode = $_POST['item-code'];
$isSale = $_POST['is-on-sale'];
$salePercent;

if($isSale==1){
    if(empty($_POST['sale-percentage']) OR ($_POST['sale-percentage']==00)){
        echo "Please provide valid percentage value.";
        return;
    } else $salePercent = $_POST['sale-percentage'];
} else $salePercent = 0;

$stringQuery = "UPDATE vc_products SET issale='$isSale', salepercent='$salePercent' WHERE code='$itemCode'";
$updateQuery = mysqli_query($connection, $stringQuery);
if($updateQuery) echo "good-query";
else echo mysqli_error($connection);
?>

Here is the JavaScript that handles the AJAX request:

以下是处理AJAX请求的JavaScript:

$("#products-table").on('click', 'span.sale-toggle', function(){
    var itemCode = $(this).attr('itemcode');
    var isSale = $(this).attr('issale');
    var salePercent = $(this).attr('percent');

    BootstrapDialog.show({
        title: '<span class="glyphicon glyphicon-edit"></span> Editing Sale Information.',
        message: $('<div></div>').load('forms/updatesale.php'),
        cssClass: 'edit-sale-modal',
        onshow:function(){
            //Do nothing.
        },
        onshown:function(){
            $('#update-sale-table td#item-code').html(itemCode);
            $('#update-sale-table input#itemcode').val(itemCode);
            if(isSale == 'true'){
                $('#update-sale-table select#is-sale').val('1');
                $('#update-sale-table input#sale-percentage').val(salePercent);
            } else {
                $('#update-sale-table select#is-sale').val('0');
                disableSalePercentage();
            }
        },
        buttons:[{
            label: '<span class="glyphicon glyphicon-remove"></span>',
            cssClass: 'btn-danger',
            action: function(dialog){
                dialog.close();
            }
        }, {
            label: '<span class="glyphicon glyphicon-ok"></span>',
            cssClass: 'btn-primary',
            hotkey: 13,
            action: function(dialog){
                var actionPath = $('form#update-sale-form').attr('action');
                var formData = $('form#update-sale-form').serialize();

                $.ajax({
                    url: actionPath,
                    type: 'POST',
                    data: formData,
                    beforeSend: function(){
                        //Do nothing.
                    },
                    success:function(actionResponse){
                        var response = actionResponse.trim();

                        if(response=='good-query'){
                            dialog.close();
                            BootstrapDialog.show({
                                title: '<span class="glyphicon glyphicon-ok"></span> Sale Record Updated.',
                                message: 'Sale record successfully changed.',
                                cssClass: 'sale-change-successfull',
                                buttons: [{
                                    label: '<span class="glyphicon glyphicon-ok"></span>',
                                    cssClass: 'btn-success',
                                    hotkey: 13,
                                    action: function(dialog){
                                        dialog.close();
                                    }
                                }]
                            });
                        } else {
                            var message = "<div class='alert alert-danger'>"+response+"</div>";
                            $('.response').html(message);
                        }
                    }
                });
            }
        }]
    });
});

I really need a hand here. My problem is that, my jQuery AJAX function is "redirecting" to the "form actions" url instead of performing the AJAX and returning the result. In my bootstrap dialog box, the form was loaded and it has a button that listens to an event where enter key is pressed and it works fine but if the percentage field is focused and the enter key is hit the page redirect to the form action and not performing the ajax call. No error displayed so i cannot troubleshoot the error but if the check button on the modal box is clicked, everything works fine. it only redirect when i am inputting the percentage value and hit enter which is most end users usually do. I really need some help here. Please spare me a little bit of your time and check what is wrong with my $.ajax() call, I really think there is something wrong with it but I just cant figure it out. Please, I need some help.

我真的需要一只手。我的问题是,我的jQuery AJAX函数是“重定向”到“表单操作”URL而不是执行AJAX并返回结果。在我的引导程序对话框中,表单已加载,并且它有一个按钮,用于侦听按下输入键的事件,并且它工作正常但如果百分比字段被聚焦并且按下回车键,页面将重定向到表单操作,没有执行ajax调用。没有显示错误,所以我无法解决错误,但如果单击模态框上的检查按钮,一切正常。它只在我输入百分比值时重定向并且输入大多数最终用户通常所做的输入。我真的需要一些帮助。请给我一点时间,并检查我的$ .ajax()调用有什么问题,我真的认为它有问题,但我无法弄明白。拜托,我需要一些帮助。

1 个解决方案

#1


2  

Hitting enter in an input field fires the submit event of the form. So what you need to do, is to attach a handler to that event, rather than the button's click event.

点击输入字段中的输入将触发表单的提交事件。所以你需要做的是将一个处理程序附加到该事件,而不是按钮的click事件。

That will catch both when the user clicks a submit button or hits enter on any input fields in the form.

当用户单击提交按钮或在表单中的任何输入字段上输入时,这将同时捕获。

$(function() {
    $("#update-sale-form").on("submit", function(event) {
        event.preventDefault();
        var form = $(event.target);

        var actionPath = form.attr("action");
        var formData = form.serialize();

        // --------------------------
        // Insert your ajax code here
        // --------------------------

        return false;
    });
});

You also need to change the action of your OK button to perform a submit on the form

您还需要更改“确定”按钮的操作以在表单上执行提交

action: function(dialog) {
    $("#update-sale-form").submit();   
}

Bonus info

When finding html elements by their ID, there's nothing gained by using long selectors that include ancestor details.

当通过ID找到html元素时,使用包含祖先细节的长选择器没有任何好处。

$("#itemcode")

is not only easier to read, but also faster than

不仅更容易阅读,而且速度更快

$("#update-sale-table input#itemcode")

Whenever it needs to find an element by it's ID, jquery uses the browser's native document.getElementById('...') function, which is extremely fast. However, when including ancestor details in the selector, jquery has to verify that the found element does infact have the correct ancestor elements. A step it can skip entirely, if you only use the ID in the selector.

每当需要通过它的ID查找元素时,jquery就会使用浏览器的原始document.getElementById('...')函数,这非常快。但是,当在选择器中包含祖先细节时,jquery必须验证找到的元素是否确实具有正确的祖先元素。如果您只在选择器中使用ID,则可以完全跳过该步骤。

#1


2  

Hitting enter in an input field fires the submit event of the form. So what you need to do, is to attach a handler to that event, rather than the button's click event.

点击输入字段中的输入将触发表单的提交事件。所以你需要做的是将一个处理程序附加到该事件,而不是按钮的click事件。

That will catch both when the user clicks a submit button or hits enter on any input fields in the form.

当用户单击提交按钮或在表单中的任何输入字段上输入时,这将同时捕获。

$(function() {
    $("#update-sale-form").on("submit", function(event) {
        event.preventDefault();
        var form = $(event.target);

        var actionPath = form.attr("action");
        var formData = form.serialize();

        // --------------------------
        // Insert your ajax code here
        // --------------------------

        return false;
    });
});

You also need to change the action of your OK button to perform a submit on the form

您还需要更改“确定”按钮的操作以在表单上执行提交

action: function(dialog) {
    $("#update-sale-form").submit();   
}

Bonus info

When finding html elements by their ID, there's nothing gained by using long selectors that include ancestor details.

当通过ID找到html元素时,使用包含祖先细节的长选择器没有任何好处。

$("#itemcode")

is not only easier to read, but also faster than

不仅更容易阅读,而且速度更快

$("#update-sale-table input#itemcode")

Whenever it needs to find an element by it's ID, jquery uses the browser's native document.getElementById('...') function, which is extremely fast. However, when including ancestor details in the selector, jquery has to verify that the found element does infact have the correct ancestor elements. A step it can skip entirely, if you only use the ID in the selector.

每当需要通过它的ID查找元素时,jquery就会使用浏览器的原始document.getElementById('...')函数,这非常快。但是,当在选择器中包含祖先细节时,jquery必须验证找到的元素是否确实具有正确的祖先元素。如果您只在选择器中使用ID,则可以完全跳过该步骤。