使用JavaScript将动态数组作为不同的变量发布

时间:2015-04-18 06:40:14

标签: javascript php

我试图动态添加主题和获得的成绩的字段,但是在使用java脚本发布这些变量时出现错误“Undefined index:subject in ...”。 我的发布机制可能会遗漏一些内容。请注意,在表单数据中没有放置id =“subject”以避免仅为一个主题选择id,并且使用name =“subject []”来显示数组,但是我 似乎不知道如何在java脚本中表示这一点,我们将在下面看到。

表格数据如下;

            <tr>
                        <td colspan="6"><div align="center"><strong>
                          <p style="color:#930">Academic Qualification</p>
                        </strong></div></td>
                      </tr>

                              <?php
                     require_once("connection/connectPDO.php");
                     $sql="CALL sp_getSubjects()"; 

                        //Initiate and Call Stored Procedure Using  PDO
                                $pdo = new PDOConfig();
                                $resultsSubject = $pdo->query($sql);
                                foreach($resultsSubject as $rowSubject)
                                        {
                    ?> 
                              <tr>
                <td width="35%" colspan="3"><div align="right"><?php echo $rowSubject['SubjectName']; ?>:<input name="subject[]" type="hidden" value="<?php echo $rowSubject['SubjectID']; ?>" /></div></td>
                        <td width="65%" colspan="3"><select name="grades[]" id="grades" class="validate[required]">
                          <option  value="">--Select Grade--</option>
                                     <?php

                    $sql="CALL sp_grabGrades()"; 

                                //Initiate and Call Stored Procedure Using PDO
                                $pdo = new PDOConfig();
                                $resultset = $pdo->query($sql);
                                foreach($resultset as $row)
                                        {

                    ?>
                       <option value="<?php echo $row['GradeObtainedID']; ?>"> <?php echo $row['Grade']; ?> </option>
                                <?php } ?>
                        </select></td>
                                 <?php } ?>
                      </tr>

表格看起来像这样

学历资格

英语&lt; - 选择 - &gt;

生物学&lt; - 选择 - &gt;

科学&lt; - 选择 - &gt;

java脚本代码如下;

            $(document).ready(function(){
                $("#submit").click(function(){
                     //if invalid do nothing
                     if(!$("#formD").validationEngine('validate')){
                     return false;
                      } 
                    var vgrades = $("#grades").val();
                    var vsubject = $("#subject").val();

                    $.post("sendInitialApplication.php", 
                        {
                            grades : vgrades,
                            subject : vsubject
                        /*Handles response from server*/
                        function(response){
                            alert(response);
                        });
                    alert("You are here");
                });
            });

PHP代码“sendInitialApplication.php”如下

            <?php
                $method = $_SERVER['REQUEST_METHOD'];


                function connect(){
                    try{
                        $dbConn = new PDO('mysql:host=localhost; dbname=student', 'root', 'root');
                        $dbConn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                        return $dbConn;
                    }
                    catch(PDOException $e){
                        echo $e->getMessage();
                    }
                }

                /*Checks if method is HTTP POST*/
                if(strtolower($method) == 'post'){

                    $grades = addslashes($_POST['grades']);
                    $subjects = addslashes($_POST['subject']);

                    try {

                        $dbHandler = connect();
                        $dbHandler->beginTransaction();

                        //Saving Various subjects with distinct grade obtained
                        foreach($subjects as $key => $subject)
                        {

                        $setIndexSubject = 'CALL sp_sendIndexSubject(:vSubjectID,:vGradeObtainedID)';
                        $stmt_subject = $dbHandler->prepare($setIndexSubject);
                        $stmt_subject->bindValue(':vSubjectID', $subject);
                        $stmt_subject->bindValue(':vGradeObtainedID', $grades[$key]);
                        $stmt_subject->execute();
                        $stmt_subject->closeCursor();
                        }

                        $dbHandler->commit();

                        echo "The Operation was Successful!!!!!!";

                    } catch (PDOException $e) {
                        $dbHandler->rollback();
                        die($e->getMessage());
                    }

                }else{
                    echo "Oops! Make sure Method is POST";
                }
            ?>

1 个答案:

答案 0 :(得分:0)

我期待$ _POST ['subject']和$ _POST ['grade']应该是数组。比你不能使用$ subject = addslashes($ _ POST ['subject']),但$ subject = $ _POST ['subject']。在数组上调用addslashes会抛出PHP警告并返回NULL。

编辑: 我建议修改代码的逻辑。 输入类型隐藏,具有主题ID,将无法正常工作,如您所期望的那样。修改你的清单:

// ... obtaining subjects from db ...
foreach($resultsSubject as $rowSubject) {
?>
  <tr>
    <td>
      <select name="grade[<?= $rowSubject['SubjectID']; ?>]">
        <option  value="">--Select Grade--</option>
        <?php
        // ... obtaining grades from db ...
        foreach($resultset as $row) {
        ?>
        <option value="<?php echo $row['GradeObtainedID']; ?>"> <?php echo $row['Grade']; ?> </option>
        <?php
        }
        ?>
      </select>
    </td>
  </tr>
<?php
}

比序列化表格应该返回数组:

grade = array (
  subjectID1 => selectedGradeId,
  subjectID2 => selectedGradeId,
  ...
)

sendInitialApplication.php中的数据处理:

// prepare db transaction
$grades = $_POST['grade'];
foreach ($grades as $subject => $grade) {
  $setIndexSubject = 'CALL sp_sendIndexSubject(:vSubjectID,:vGradeObtainedID)';
  $stmt_subject = $dbHandler->prepare($setIndexSubject);
  $stmt_subject->bindValue(':vSubjectID', $subject);
  $stmt_subject->bindValue(':vGradeObtainedID', $grade);
  $stmt_subject->execute();
  $stmt_subject->closeCursor();
}
// close db transaction