Cant upload image mysql php with modal form and ajax.js

here is my my modal form

<div class="modal fade" id="modalForExam" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
   <form class="refreshFrm" id="addExamFrm" method="post">
     <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Add Exam</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <div class="col-md-12">
          <div class="form-group">
            <label>Select Course</label>
            <select class="form-control" name="courseSelected">
              <option value="0">Select Course</option>
              <?php 
                $selCourse = $conn->query("SELECT * FROM course_tbl ORDER BY cou_id DESC");
                if($selCourse->rowCount() > 0)
                {
                  while ($selCourseRow = $selCourse->fetch(PDO::FETCH_ASSOC)) { ?>
                     <option value="<?php echo $selCourseRow['cou_id']; ?>"><?php echo $selCourseRow['cou_name']; ?></option>
                  <?php }
                }
                else
                { ?>
                  <option value="0">No Course Found</option>
                <?php }
               ?>
            </select>
          </div>

          <div class="form-group">
            <label>Exam Time Limit</label>
            <select class="form-control" name="timeLimit" required="">
              <option value="0">Select time</option>
              <option value="10">10 Minutes</option> 
              <option value="20">20 Minutes</option> 
              <option value="30">30 Minutes</option> 
              <option value="40">40 Minutes</option> 
              <option value="50">50 Minutes</option> 
              <option value="60">60 Minutes</option> 
            </select>
          </div>

          <div class="form-group">
            <label>Question Limit to Display</label>
            <input type="number" name="examQuestDipLimit" id="" class="form-control" placeholder="Input question limit to display">
          </div>

          <div class="form-group">
            <label>Exam Title</label>
            <input type="" name="examTitle" class="form-control" placeholder="Input Exam Title" required="">
          </div>

          <div class="form-group">
            <label>Exam Description</label>
            <textarea name="examDesc" class="form-control" rows="4" placeholder="Input Exam Description" required=""></textarea>
          </div>

          <div class="form-group">

          <form action=""  method="post" enctype="multipart/form-data">
            <label>Select Image File:</label>
            <input type="file" name="fileToUpload" id="fileToUpload">
            
        </form>
  
 
      </div>

        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="submit" class="btn btn-primary" >Add Now</button>
      </div>
    </div>
   </form>
  </div>
</div>

here is my ajax.js codeblock

$(document).on("submit","#addExamFrm" , function(){
  $.post("query/addExamExe.php", $(this).serialize() , function(data){
    if(data.res == "noSelectedCourse")
   {
      Swal.fire(
          'No Course',
          'Please select course',
          'error'
       )
    }
    if(data.res == "noSelectedTime")
   {
      Swal.fire(
          'No Time Limit',
          'Please select time limit',
          'error'
       )
    }
    if(data.res == "noDisplayLimit")
   {
      Swal.fire(
          'No Display Limit',
          'Please input question display limit',
          'error'
       )
    }

     else if(data.res == "exist")
    {
      Swal.fire(
        'Already Exist',
        data.examTitle.toUpperCase() + '<br>Already Exist',
        'error'
      )
    }
    else if(data.res == "success")
    {
      Swal.fire(
        'Success',
        data.examTitle.toUpperCase() + '<br>Successfully Added',
        'success'
      )
          $('#addExamFrm')[0].reset();
          $('#course_name').val("");
          refreshDiv();
    }
  },'json')
  return false;
});

The main problem is here:

<?php 
 include("../../../conn.php");

 extract($_POST);

 $selCourse = $conn->query("SELECT * FROM exam_tbl WHERE ex_title='$examTitle' ");

 if($courseSelected == "0")
 {
  $res = array("res" => "noSelectedCourse");
 }
 else if($timeLimit == "0")
 {
  $res = array("res" => "noSelectedTime");
 }
 else if($examQuestDipLimit == "" && $examQuestDipLimit == null)
 {
  $res = array("res" => "noDisplayLimit");
 }
 else if($selCourse->rowCount() > 0)
 {
  $res = array("res" => "exist", "examTitle" => $examTitle);
 }
 else
 {
  
  //$filename = $_FILES['fileToUpload']['name'];
  //$target_file = '/includes/uploads/'.$filename;
    
    $filename = 'jk';
  $insExam = $conn->query("INSERT INTO exam_tbl(cou_id,ex_title,ex_time_limit,ex_questlimit_display,ex_description, filename) VALUES('$courseSelected','$examTitle','$timeLimit','$examQuestDipLimit','$examDesc','$filename') ");
  if($insExam)
  {
    $res = array("res" => "success", "examTitle" => $examTitle);
  }
  else
  {
    $res = array("res" => "failed", "examTitle" => $examTitle);
  }


 }

 echo json_encode($res);
 ?>

it says undefined array key “fileToUpload”

The jquery serialize method doesn’t handle file uploads. You would want to use a FormData object - Using FormData Objects - Web APIs | MDN

You can reference the form and create a FormData object using -

// reference the form
var form = $('#addExamFrm')[0];
// create FormData object
var formData = new FormData(form);

You may need to switch to using the jquery .ajax method since you must set -

processData: false,
contentType: false,

and I don’t know if you can set these easily when using the .post method.

Note: for the required attribute to work for a select/option field, the first prompt option must use an empty string ‘’ for the value.

Your uploadfield " fileToUpload" is wrapped in a form-tag, so you have a (sub)form within your mainform "
#addExamFrm".

Serializing your main-form won’t add the fields of the sub-form to the data-to-post, so “fileToUpload” is undefined after POST.

Sponsor our Newsletter | Privacy Policy | Terms of Service