0

Am trying to dynamically add the fields for subjects and the grades obtained, but am getting an error "Undefined index: subject in..." when posting those variables using java script. Could there be something am missing with my posting mechanism. Notice that in the form data am not puting id="subject" to avoid picking the id for only one subject, and am using name="subject[]" to show an array, but I dont seem to know how to represent this in the java script as we will see below.

form data as follows;

            <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>

the form looks like this

Academic Qualification

English <--select-->

Biology <--select-->

Science <--select-->

the java script code is as follows;

            $(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");
                });
            });

the PHP code "sendInitialApplication.php" is as follows

            <?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";
                }
            ?>
Vaibhav Mule
  • 5,016
  • 4
  • 35
  • 52
mountain
  • 106
  • 1
  • 14

1 Answers1

0

I'm expecting that $_POST['subject'] and $_POST['grades'] should be array. Than you cannot use $subjects = addslashes($_POST['subjects']), but $subjects = $_POST['subjects']. Calling addslashes on array throws PHP warning and returns NULL.

Edit: I suggest modify logic of your code. Input type hidden, with subject id, will not work, as you expects. Modify your list:

// ... 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
}

Than serialized form should return array:

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

And data processing in 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
Kepi
  • 374
  • 2
  • 7
  • thanks but that still didnt work. subject is not being defined, how best can we show this post – mountain Apr 18 '15 at 08:37
  • Try to serialize form data on submit as shown here: http://stackoverflow.com/questions/15173965/serializing-and-submitting-a-form-with-jquery-post-and-php – Kepi Apr 18 '15 at 08:46
  • Nothing still, we have a problem with the posting of subject – mountain Apr 18 '15 at 17:32
  • I've modified answer. Try to chanfe your grade selects, and data processing logic. – Kepi Apr 18 '15 at 19:37
  • the subjects are entered dynamically on the db, so we can not pre_define like in the array "grade = array(subjectID1 => selectedGradeId,...) ", the subjects can grow anytime and I wish not to go back to increasing the mentioned array. the subjects are not static. A user should enter subjects and on that form they should show. – mountain Apr 19 '15 at 04:04
  • I don't see problem. Subjects are readed from database. So list of subject depends on selection logic. Each user should have different subjects list. And submit will return only listed subjects, there are no need for static list. – Kepi Apr 19 '15 at 06:55
  • Please understand the logic of how I want this to run. Please read through my question and the comments again. These are dynamic fields, every user sees all the subjects as the list grows in the DB. I have another form where I enter subjects and store them in a separate table. the user from the Form front end sees the subjects and so as the select grade input stub . – mountain Apr 21 '15 at 06:56