douxin9135 2015-12-30 12:15
浏览 151
已采纳

单击提交按钮时,使用jquery / AJAX提交表单无效

I am trying to submit a form with jquery/AJAX but my function is never called when I am clicking on the submit button.

My website looks like that: CarMenu.php

<html lang="en">
<html>
<head>
   <meta charset="ISO-8859-1">
   <title>ArsenalAutoBrokers - Backend - add car</title>
   <link rel="stylesheet" href="../js/jquery-ui-1.11.4/jquery-ui.min.css"     type="text/css"/>
   <link rel="stylesheet" href="../js/jquery-ui-1.11.4/jquery-ui.css" type="text/css"/>
   <link rel="stylesheet" href="../js/jquery-ui-1.11.4/jquery-ui.theme.css" type="text/css"/>
   <link rel="stylesheet" href="../js/jquery-ui-1.11.4/jquery-ui.structure.css" type="text/css"/>
   <link rel="stylesheet" href="../css/carForm.css" type="text/css"/>
   <script charset="UTF8" src="../js/jquery/jquery-1.11.3.js"></script>
   <script charset="UTF8" src="../js/jquery-ui- 1.11.4/external/jquery/jquery.js"></script>
   <script charset="UTF8" src="../js/jquery-ui-1.11.4/jquery-ui.js"></script>
   <script charset="UTF8" src="../js/app/carForm.js"></script>
   <script charset="UTF8" src="../js/app/addCar.js"></script>
</head>
<body>
   <div id="container">
      <div id="leftMenuContainer">
         <ul id="menu">
            <li id="addCarItem">Add car</li>
            <li id="saveCarItem">Edit cars</li>
         </ul> 
      </div>
      <div id="rightMainContent">

      </div>
      <div class="clear"></div>
    </div>
  </body>
</html>

On that page, I am using jquery menu and I am loading the data into the div with the id 'rightMainContent'.

The javascript code to do this looks like: carForm.js

$(document).ready(function () {
   $( "#menu" ).menu({
    select: function(event, ui) {
        if (ui.item.attr('id') === 'addCarItem') {
           $("#rightMainContent").load(
             '/CarDealer/CarForm/CreateCar/AddCar.php');       
        }
    }
});  
});

If you are clicking on the 'addCar' menu item parts of the site will load from this php site:

 <script type="text/javascript">

 $('input[type=submit]').button();
 //$('#activeCheck').button();
 $("#activeCheck").attr('checked','checked');
 $('#saveButton').hide();
 $('#tabs').tabs();
 $('#accordion' ).accordion({heightStyle: "content"});

 $('#tabs').tabs({
     activate: function (event, ui) {
         var act = $("#tabs").tabs("option", "active");
         if (act == 0 || act == 1) {
            $('#saveButton').hide();
         } else {
            $('#saveButton').show();
         }
     }
 });  

 $('#fileToUpload').on('change', function(){ 
   var fileSelect = document.getElementById('fileToUpload');
   var files = fileSelect.files;

   if (files.length > 10) {
     $('.info').html('The file upload is limited to <font color="red"><b>10 pictures per car</b></font>.<br>Only the 1st ten pictures will be stored.');
     $('.info').show();
   } else {
        $('.info').html('');
     $('.info').hide();
   }

 });

 </script>

 <form id="carSaveForm"
    action="/CarDealer/CarForm/CreateCar/CarCreation.php" method="POST"
    enctype="multipart/form-data">
    <div id="tabs">
        <ul>
            <li><a href="#tabsGen">General Car Information</a></li>
            <li><a href="#tabsDescr">Car Descriptions</a></li>
            <li><a href="#tabsPics">Picture Upload</a></li>
        </ul>
        <div id="tabsGen">
    <?php include($_SERVER['DOCUMENT_ROOT']."/CarDealer/CarForm/CreateCar/carGeneralData.php"); ?>
   </div>
        <div id="tabsDescr">
    <?php include($_SERVER['DOCUMENT_ROOT']."/CarDealer/CarForm/CreateCar/carDescriptions.php"); ?>
   </div>
        <div id="tabsPics">
    <?php include($_SERVER['DOCUMENT_ROOT']."/CarDealer/CarForm/CreateCar/PictureUpload.php"); ?>

   </div>
    </div>
    <br> <input id="saveButton" type="submit" name="submit" value="save" />
 </form>    

This site is containg only form elements like input buttons, file pickers, etc.

Well, so far so good. Everything is displaying properly but if I am clicking the submit button this function isn't getting called: addCar.js

$('#carSaveForm').on('submit', function(event){
        event.preventDefault();

        var formData = new FormData();
        // get the form data
        // there are many ways to get this data using jQuery (you can use the class or id also)
        formData.append('carBrand'               , $('input[name=carBrand]').val());
        formData.append('carModelYear'           , $('input[name="carModelYear"]').val());
        formData.append('carModel'               , $('input[name=carModel]').val());
        formData.append('carTrim'                , $('input[name="carTrim"]').val());
        formData.append('carDriveTrain'          , $('input[name="carDriveTrain"]').val());
        formData.append('carCondition'           , $('input[name="carCondition"]').val());
        formData.append('carType'                , $('input[name="carType"]').val());
        formData.append('carFuelType'            , $('input[name="carFuelType"]').val());
        formData.append('carTransmission'        , $('input[name="carTransmission"]').val());
        formData.append('carEngine'              , $('input[name="carEngine"]').val());
        formData.append('carCylinder'            , $('input[name="carCylinder"]').val());
        formData.append('carMileage'             , $('input[name="carMileage"]').val());
        formData.append('carExteriorColor'       , $('input[name="carExteriorColor"]').val());
        formData.append('carInteriorColor'       , $('input[name="carInteriorColor"]').val());
        formData.append('carLocation'            , $('input[name="carLocation"]').val());
        formData.append('carVin'                 , $('input[name="carVin"]').val());
        formData.append('carStock'               , $('input[name="carStock"]').val());
        formData.append('carPrice'               , $('input[name="carPrice"]').val());
        formData.append('carPriceDetails'        , $('input[name="carPriceDetails"]').val());
        formData.append('carTax'                 , $('input[name="carTax"]').val());
        formData.append('carTaxDetails'          , $('input[name="carTaxDetails"]').val());
        formData.append('carCurrency'            , $('input[name="carCurrency"]').val());
        formData.append('carOnline'              , $('input[name="carOnline"]').val());
        formData.append('carDescr'               , $('input[name="carDescr"]').val());
        formData.append('carBodyDescr'           , $('input[name="carBodyDescr"]').val());
        formData.append('carDriveTrainDescr'     , $('input[name="carDriveTrainDescr"]').val());
        formData.append('carExteriorDescr'       , $('input[name="carExteriorDescr"]').val());
        formData.append('carElectronicsDescr'    , $('input[name="carElectronicsDescr"]').val());
        formData.append('carSaftyFeaturesDescr'  , $('input[name="carSaftyFeaturesDescr"]').val());
        formData.append('carSpecialFeaturesDescr', $('input[name="carSpecialFeaturesDescr"]').val());

        var fileSelect = document.getElementById('fileToUpload');
        var files = fileSelect.files;
        // Loop through each of the selected files.
        for (var i = 0; i < files.length; i++) {
          var file = files[i];

          // Add the file to the request.
          formData.append('files[]', file, file.name);
        }

        // process the form
        $.ajax({
           type        : 'POST', // define the type of HTTP verb we want to use (POST for our form)
           url         : '/CarDealer/CarForm/createCar/carCreation.php', // the url where we want to POST
           data        : formData, // our data object
           contentType: false,
           processData: false,
           success: function (data) {
               $('.success').fadeIn(200).show();
               $('.error').fadeOut(200).hide();
           },
           error: function (data) {
               $('.success').fadeIn(200).hide();
               $('.error').fadeOut(200).show();
           }

        });
        return false;
    });

I have no clue why this function is never getting called, I have tried everything, I have googled a lot but I am not getting it. I am searching for the error the whole day but I can't see it.

Please help me.

Your help is apreciated.

Thanks in advance.

  • 写回答

3条回答 默认 最新

  • dongman5539 2015-12-30 12:26
    关注

    jQuery is only aware of the elements in the page at the time that it runs, so new elements added to the DOM are unrecognized by jQuery. To combat that use event delegation, bubbling events from newly added items up to a point in the DOM that was there when jQuery ran on page load. Many people use document as the place to catch the bubbled event, but it isn't necessary to go that high up the DOM tree. Ideally you should delegate to the nearest parent that exists at the time of page load.

    For instance, this button has been added to the DOM via AJAX:

    <input id="saveButton" type="submit" name="submit" value="save" />
    

    In order to properly handle this (if it is the only form with this id added to the page) is to delegate the click or submit event:

    $(document).on('click', '#saveButton', function(event) {...
    

    In addition, if you continue to add forms as you show here, you will have duplicate id's in your page and id's must be unique. Failure to make them unique will result in a number of problems.

    Make sure to watch the AJAX request / response in the browser's console as outlined here to find and correct errors that you may be having.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 关于温度改变石墨烯介电性能(关键词-介电常数)
  • ¥150 HDMI分路器LT86102 的输出在890MHz频点处EMC超标8DB
  • ¥15 druid(相关搜索:数据库|防火墙)
  • ¥15 大一python作业
  • ¥15 preLaunchTask"C/C++: aarch64- apple-darwin22-g++-14 生成活动 文件”已终止,退出代码为-1。
  • ¥60 如何鉴定微信小程序数据被篡改过
  • ¥18 关于#贝叶斯概率#的问题:这篇文章中利用em算法求出了对数似然值作为概率表参数,然后进行概率表计算,这个概率表是怎样计算的呀
  • ¥20 C#上传XML格式数据
  • ¥15 elementui上传结合oss接口断点续传,现在只差停止上传和继续上传,各大精英看下
  • ¥20 手机截图相片分辨率降低一半