【问题标题】:dynamically generated radio buttons name property array index increment动态生成的单选按钮名称属性数组索引增量
【发布时间】:2020-12-05 16:18:06
【问题描述】:

我想在单击 save1 按钮时提交我的表单数据,而不使用 ajax 和 jquery 刷新页面。我是新手,请帮忙。 这是我的 jquery 和 ajax 脚本。在这里,我将所有数据字段存储在数组中,因为我的表单字段可以动态生成。 当我跳过 jquery 和 ajax 部分,并使用 form action='savedata.php' 提交表单数据时,数据将被插入数据库。但随后页面被重定向到 savedata.php 文件。

<script type="text/javascript">
  $(document).ready(function()

{

            $('input[name="instituteName[]"]').each(function(){ 
              instituteName.push($(this).text());
            });
            var universityName= [];
            $('input[name="universityName[]"]').each(function(){
              universityName.push($(this).text());
            });
            var duration= [];
            $('input[name="duration[]"]').each(function(){
              duration.push($(this).text());
            });
            var division= [];
            $('input[name="division[]"]').each(function(){
              division.push($(this).text());
            });
            var obtained= [];
            $('input[name="obtained[]"]').each(function(){
              obtained.push($(this).text());
            });
            var course_type= [];
            $('input[name="course_type[]"]').each(function(){
              course_type.push($(this).text());
            });
            var major= [];
            $('input[name="major[]"]').each(function(){
              major.push($(this).text());
            });
            var roll_no= [];
            $('input[name="roll_no[]"]').each(function(){
              roll_no.push($(this).text());
            });
            var building_no= [];
            $('input[name="building_no[]"]').each(function(){
              building_no.push($(this).text());
            });
            var city= [];
            $('input[name="city[]"]').each(function(){
              city.push($(this).text());
            });
            var state= [];
            $('input[name="state[]"]').each(function(){
              state.push($(this).text());
            });
            var pin= [];
            $('input[name="pin[]"]').each(function(){
              pin.push($(this).text());
            });
            var landline= [];
            $('input[name="landline[]"]').each(function(){
              landline.push($(this).text());
            });
            var mark_sheets= [];
            $('input[name="mark_sheets[]"]').each(function(){
              mark_sheets.push($(this).text());
            });
            var degree_certificate= [];
            $('input[name="degree_certificate[]"]').each(function(){
              degree_certificate.push($(this).text());
            });
            var provisional_degree= [];
            $('input[name="provisional_degree[]"]').each(function(){
              provisional_degree.push($(this).text());
            });

            $.ajax({
              
              url:"save_secondary_details.php",
              method:"POST",
              data:{instituteName:instituteName, universityName:universityName, duration:duration, division:division, obtained:obtained, course_type:course_type, major:major, roll_no:roll_no, building_no:building_no, city:city, state:state, pin:pin, landline:landline, mark_sheets:mark_sheets, degree_certificate:degree_certificate, provisional_degree:provisional_degree},
              success:function(data)
              {
                alert(data);

              }
            });

          });

  });
  
  
</script>

我正在尝试将存储在表单输入中的所有值传递给 ajax,然后将其存储到数据库中。

这是我的 PHP 代码:

<?php 
              include('../includes/dbconnection.php');
              //error_reporting(0);
              if(isset($_POST['save1']))
              {
                $email="farhan.khan@ifim.edu.in";
                $instituteName= $_POST['instituteName'];
                $universityName= $_POST['universityName'];
                $duration= $_POST['duration'];
                $division= $_POST['division'];
                $obtained= $_POST['obtained'];
                $course_type= $_POST['course_type'];
                $major= $_POST['major'];
                $roll_no= $_POST['roll_no'];
                $building_no= $_POST['building_no'];
                $city= $_POST['city'];
                $state= $_POST['state'];
                $pin= $_POST['pin'];
                $landline= $_POST['landline'];
                $mark_sheets= $_POST['mark_sheets'];
                $degree_certificate= $_POST['degree_certificate'];
                $provisional_degree= $_POST['provisional_degree'];

                foreach ($instituteName as $key => $value) {
                  $save= "INSERT INTO `candidate_secondary_education`(`email`,`inst_name`,`board`,`duration`,`percentage`,`obtained`,`course_type`,`majored_in`,`reg_no`,`street`,`city`,`state`,`pin`,`contact`,`mark_sheet`,`degree`,`provisional_degree`) VALUES ('$email','$value','$universityName[$key]','$duration[$key]','$division[$key]','$obtained[$key]','$course_type[$key]','$major[$key]','$roll_no[$key]','$building_no[$key]','$city[$key]','$state[$key]','$pin[$key]','$landline[$key]','$mark_sheets[$key]','$degree_certificate[$key]','$provisional_degree[$key]')";

                  $query = mysqli_query($con, $save);
                  if(!$query)
                  {
                    echo mysqli_error($con);
                  }
                  else
                  {

                    echo '<script type="text/javascript">'; 
                    echo 'alert("Saved.");'; 
                    
                    echo '</script>';
                  }
                }
              }
            ?>

但是数据没有被插入到数据库中。

这是我的 HTML 文件:

<div class="row">


                    <div class="col-md-12 col-sm-12 ">
                    <div class="x_panel tile " > 
                    <div class="x_title">
                      <h2>Secondary Education Details</h2>
                    <ul class="nav navbar-right panel_toolbox">
                      <li><a class="collapse-link"><i class="fa fa-chevron-up"></i></a>    </li>
                      </li>
                    </ul>
                      <div class="clearfix"></div>
                      </div>
                        <div class="x_content">
                        
                        <form class="form-horizontal form-label-left" method="post" id="secondary_education_details" action="save_secondary_details.php">

                        <div class="form-group row">
                        
                          <label class="col-form-label col-md-3 col-sm-3 label-align" for="institute-name">Name of the Institute/School/College: <span class="required">*</span>
                          </label>
                          <div class="col-md-6 col-sm-6 ">
                          <input type="text" name="instituteName[]" required="required" class="form-control  ">
                          </div>  

                        </div>


                        <div class="form-group row">
                          <label class="col-form-label col-md-3 col-sm-3 label-align" for="university-name">Board/University: <span class="required">*</span>
                          </label>
                          <div class="col-md-6 col-sm-6 ">
                          <input type="text"  name="universityName[]" required="required" class="form-control ">
                          </div>
                        </div>


                      <div class="form-group row">
                        <label class="col-form-label col-md-3 col-sm-3 label-align" for="duration">Duration of Study (specify month & year): <span class="required">*</span>
                        </label>
                        <div class="col-md-6 col-sm-6 ">
                          <input type="text"  name="duration[]" required="required" class="form-control ">
                        </div>
                      </div>

                      <div class="form-group row">
                        <label class="col-form-label col-md-3 col-sm-3 label-align" for="division">Division/Class/% : <span class="required">*</span>
                        </label>
                        <div class="col-md-6 col-sm-6 ">
                          <input type="text"  name="division[]" required="required" class="form-control  ">
                        </div>  
                      </div>

                        <div class="form-group row">
                        <label class="col-form-label col-md-3 col-sm-3 label-align" for="degree-obtained">Degree Obtained : <span class="required">*</span>
                        </label>
                        <div class="col-md-6 col-sm-6 ">
                            <p style="
                            margin-top:8px;">
                                Yes:
                                <input type="radio" class="flat" name="obtained[0]"  value="yes" required="required" /> 
                                No:
                                <input type="radio" class="flat" name="obtained[0]"  value="no" />
                            </p>
                        </div>  
                      </div>

                      <div class="form-group row">
                        <label class="col-form-label col-md-3 col-sm-3 label-align" for="course-type">Course Type: <span class="required">*</span>
                        </label>
                        <div class="col-md-6 col-sm-6 ">
                            <p style="
                            margin-top:8px;">
                                Regular:
                                <input type="radio" class="flat" name="course_type[0]"  value="regular" required="required" /> 
                                Distance:
                                <input type="radio" class="flat" name="course_type[0]"  value="distance" />
                            </p>
                        </div>  
                      </div>

                      <div class="form-group row">
                        <label class="col-form-label col-md-3 col-sm-3 label-align" for="major">Majored in:<span class="required">*</span>
                        </label>
                        <div class="col-md-6 col-sm-6 ">
                          <input type="text"  name="major[]" required="required" class="form-control  ">
                        </div>  
                      </div>

                      <div class="form-group row">
                        <label class="col-form-label col-md-3 col-sm-3 label-align" for="roll-no">Student ID/Enrolment/Registration/Roll No: <span class="required">*</span>
                        </label>
                        <div class="col-md-6 col-sm-6 ">
                          <input type="text"  name="roll_no[]" required="required" class="form-control  ">
                        </div>  
                      </div>
                      <br><h4><center>Address of Institute/School/College</center></h4><br>
                      <div class="form-group row">
                        <label class="col-form-label col-md-3 col-sm-3 label-align" for="building-no">Building No & Street: <span class="required">*</span>
                        </label>
                        <div class="col-md-6 col-sm-6 ">
                          <textarea class="form-control"  name="building_no[]" required="required" ></textarea>
                        </div>
                        </div>
                        <div class="form-group row">
                        <label class="col-form-label col-md-3 col-sm-3 label-align" for="city">City: <span class="required">*</span>
                        </label>
                        <div class="col-md-6 col-sm-6 ">
                          <input type="text" class="form-control"  name="city[]" required="required" >
                        </div>
                        </div>
                        <div class="form-group row">
                        <label class="col-form-label col-md-3 col-sm-3 label-align" for="state">State: <span class="required">*</span>
                        </label>
                        <div class="col-md-6 col-sm-6 ">
                          <input type="text" class="form-control"  name="state[]" required="required" >
                        </div>
                        </div>
                        <div class="form-group row">
                        <label class="col-form-label col-md-3 col-sm-3 label-align" for="pin">PIN: <span class="required">*</span>
                        </label>
                        <div class="col-md-6 col-sm-6 ">
                          <input type="text" class="form-control"  name="pin[]" required="required" >
                        </div>
                        </div>
                        <div class="form-group row">
                        <label class="col-form-label col-md-3 col-sm-3 label-align" for="landline">Landline: <span class="required">*</span>
                        </label>
                        <div class="col-md-6 col-sm-6 ">
                          <input type="text" class="form-control"  name="landline[]" required="required" >
                        </div>
                        </div>
                        <div class="form-group row">
                        <label class="col-form-label col-md-3 col-sm-3 label-align" for="mark-sheets">Mark Sheets: <span class="required">*</span>
                        </label>
                        <div class="col-md-6 col-sm-6 ">
                          <input type="file"  name="mark_sheets[]" required="required" >
                        </div>
                        </div>
                        <div class="form-group row">
                        <label class="col-form-label col-md-3 col-sm-3 label-align" for="degree-certificate">Degree Certificate: <span class="required">*</span>
                        </label>
                        <div class="col-md-6 col-sm-6 ">
                          <input type="file"  name="degree_certificate[]" required="required" >
                        </div>
                        </div>
                        <div class="form-group row" >
                        <label class="col-form-label col-md-3 col-sm-3 label-align" for="provisional-degree">Provisional Degree certificate: <span class="required">*</span>
                        </label>
                        <div class="col-md-6 col-sm-6 ">
                          <input type="file"  name="provisional_degree[]" required="required" >
                        </div>
                        </div>
                      <div id="001">
                        
                      </div>
                      <div class="row">
                      <span id="result"></span>
                      </div>
                      <div class="row" style="margin-top:40px;">
                        <div class="col-md-6 offset-md-9">
                          <button type="button" name="add1" value="Add more" id="add1" class="btn btn-success btn-lg" style=" padding: 12px;
                                width: 154px;border-radius: 10px;
                                ">Add more</button>
                          <button type="submit" name="save1" id="save1" value="Save1"  class="btn btn-info btn-lg" style=" padding: 12px;
                                width: 154px;border-radius: 10px;background-color: #3f51b5;
                                ">Save</button>
                        </div>
                      </div>
                      
                        
                          
                        
                      

                      </form>
                      
                    
                    </div>
                  </div>
                </div>

【问题讨论】:

  • 欢迎来到StackOverflow!我们希望你喜欢这里。请参观:stackoverflow.com/tour 并提供一个最小的、可重现的示例:stackoverflow.com/help/minimal-reproducible-example。 savedata.phpsave_secondary_details.php 有什么区别?
  • 警告:您对SQL Injections 持开放态度,应该使用参数化的prepared statements,而不是手动构建查询。它们由PDOMySQLi 提供。永远不要相信任何形式的输入!即使您的查询仅由受信任的用户执行,you are still in risk of corrupting your dataEscaping is not enough!
  • 其实只有save_secondary_details.php,没有savedata.php这样的文件。

标签: javascript html jquery arrays ajax


【解决方案1】:

将按钮类型更改为“按钮”:

<button type="button" name="save1" id="save1" value="Save1"  class="btn btn-info btn-lg" style=" padding: 12px;
                                width: 154px;border-radius: 10px;background-color: #3f51b5;
                                ">Save</button>

或阻止默认:

document.getElementById("save1").addEventListener("click", function(e){
  e.preventDefault()
});

【讨论】:

    【解决方案2】:

    一个简单的 AJAX 调用就可以做到!

    //another way to write $(document).ready(function() {
    $(function() {
        $('form').on('submit', function(event) {
            //stop default form submission
            event.preventDefault();
            //submit form via AJAX
            $.post('savedata.php', $(this).serialize())
            //show response when done
            .done(function(data) {
                console.log( data );
             });
        });
    });
    

    参考

    演示

    我现在包含一个包含 3 种表单的演示 - 当然,您可以拥有任意数量的表单 - 但只有第一个具有事件处理程序。因为我们有event.preventDefault(),所以提交时不会重定向。但是,其他两种表单将尝试重定向,因为它们没有带有event.preventDefault() 的事件处理程序。

    $(function() {
        $('#form1').on('submit', function(event) {
            event.preventDefault();
            const data=$(this).serialize();
            console.log('READY TO SUBMIT #form1 DATA VIA AJAX');
            console.log( data );
            //AJAX CALL
        });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <form id="form1">
      <label for="fname">First name:</label><br>
      <input type="text" id="fname" name="fname" placeholder="John"><br>
      <label for="lname">Last name:</label><br>
      <input type="text" id="lname" name="lname" placeholder="Doe"><br><br>
      <label for="gender">Gender:</label><br>
      <input type="radio" id="male" name="gender" value="male">
      <label for="male">Male</label><br>
      <input type="radio" id="female" name="gender" value="female">
      <label for="female">Female</label><br>
      <input type="radio" id="other" name="gender" value="other">
      <label for="other">Other</label><br><br>
      <input type="submit" value="Submit">
    </form>
    <hr>
    <form id="form2">
      <label for="fname">First name:</label><br>
      <input type="text" id="fname" name="fname" placeholder="John"><br>
      <label for="lname">Last name:</label><br>
      <input type="text" id="lname" name="lname" placeholder="Doe"><br><br>
      <label for="gender">Gender:</label><br>
      <input type="radio" id="male" name="gender" value="male">
      <label for="male">Male</label><br>
      <input type="radio" id="female" name="gender" value="female">
      <label for="female">Female</label><br>
      <input type="radio" id="other" name="gender" value="other">
      <label for="other">Other</label><br><br>
      <input type="submit" value="Submit">
    </form>
    <hr>
    <form id="form3">
      <label for="fname">First name:</label><br>
      <input type="text" id="fname" name="fname" placeholder="John"><br>
      <label for="lname">Last name:</label><br>
      <input type="text" id="lname" name="lname" placeholder="Doe"><br><br>
      <label for="gender">Gender:</label><br>
      <input type="radio" id="male" name="gender" value="male">
      <label for="male">Male</label><br>
      <input type="radio" id="female" name="gender" value="female">
      <label for="female">Female</label><br>
      <input type="radio" id="other" name="gender" value="other">
      <label for="other">Other</label><br><br>
      <input type="submit" value="Submit">
    </form>

    【讨论】:

    • 我已经尝试过将 action="" 属性保留为空,在这种情况下,我单击提交按钮后页面正在重新加载并且没有数据插入到数据库中。当我保留 action="save_secondary_details.php" 属性时,表单被重定向到 php 页面并将数据插入到数据库中。但我不希望它重定向到另一个页面。
    • (1) 确认您为表单使用了正确的选择器。 (2) 页面上有多少个表格? (3) 在浏览器开发者工具选项卡中检查控制台上的错误。
    • (1) 我使用表单 ID 作为选择器,它是 #secondary_education_details 代替“表单”(如您的回答)。 (2) 我在页面上有 5 个表单,都有不同的 id 和不同的提交按钮。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-13
    • 1970-01-01
    • 2013-05-25
    相关资源
    最近更新 更多