且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

带有多个表单的jQuery的Ajax表单提交

更新时间:2022-12-11 13:36:18

我修改了一些内容,主要是要记住:"Id属性在文档中必须是唯一的"

I have modified some things, having in mind mainly: 'Id attributes must be unique in the document'

(即使代码中没有通过id对表单元素的其他引用,也可以删除id属性)因此,我已将ID重命名,因为它们具有唯一的值,然后获取click事件以捕获任何提交的输入

(Even, If there are not other references in the code to the form elements by id then the id attribute can be removed) So I have renamed ids as they have an unique value, then I fetch the click event for catch any input submit

注意:我已经从包含最后单击元素的父级(窗体)中访问了其他元素,因为我不确定这是否是您拥有的整个HTML.

NOTE: I have accessed to the other elements from the parent (its form) which contains the last clicked element because I'm not sure if it is the entire HTML you have.

campers.php

campers.php

<form id="retro1457806069">
<input type="hidden" id="class1" name="classa" value="retro">
<input type="hidden" id="type1" name="type" value="1">
<input type="submit" id="submit1" value="Rent This Camper"></form>

<form id="two1457806069">
<input type="hidden" id="class2" name="classa" value="classtwo">
<input type="hidden" id="type2" name="type" value="1">
<input type="submit" id="submit2" value="Rent This Camper"></form>

<form id="three1457806069">
<input type="hidden" id="class3" name="classa" value="classthree">
<input type="hidden" id="type3" name="type" value="1">
<input type="submit" id="submit3" value="Rent This Camper"></form>

script.js

script.js

$(document).ready(function() {
  $("input[type=submit]").click(function(e) {
    // **Accesing by proximty of the last clicked element, and by its name.
    e.preventDefault();
    var classa = $(this).parent('form').find('input[name="classa"]').val();
    var type = $(this).parent('form').find('input[name="type"]').val();
    // Returns successful data submission message when the entered information is stored in database.
    var dataString = 'class=' + classa + '&type=' + type;
    if (classa == '' || type == '') {
      alert("Please Fill All Fields");
    } else {
      // AJAX Code To Submit Form.
      $.ajax({
        type: "POST",
        url: "campersub.php",
        data: dataString,
        cache: false,
        success: function(result) {
          window.location.assign("gear.php")

        }
      });
    }
    return false;
  });
});

我认为它必须与这些更改一起运行...

I think it must run with these changes...