Quantcast
Channel: Active questions tagged html - Stack Overflow
Viewing all articles
Browse latest Browse all 67441

My files input field keeps getting reset because of ajax which is causing 'no files selected' error

$
0
0

My file input field keeps on resetting after every 1 seconds which gives an on pressing of submit button

Unexpected token < in JSON at position 1

i have also changed the original bootstrap to basic html to discover that the error is causing by ajax request which is used to get notification, It triggers itself at every 5 sec. I thought maybe its refreshing the web page that's why it shows no file selected after every time I select a file from my hard disk I increased the time to further 15 seconds but still error persists.

html code

<form   enctype="multipart/form-data" method="post" id = 'u_excel_form'  
          name="fileinfo">

    <div class="input-group-mb-3">
       <div class="input-group-prepend">
        <input type="text" placeholder="course code" name="subject_code" 
            id="u_subject_code">
       </div>
     </div>

      <div class="input-group-mb-3">
        <div class="input-group-prepend">
         <input type="file" placeholder="Select file" id="file" name="file">
        </div>
      </div>

     <div class="form-group">
       <input type="submit" class="btn btn-success btn-lg btn-block" disabled 
        value="submit" name="submitExcel" id="u_submit_excel">
     </div>

     </form>

jquery code

       $(document.body).on("click","#u_submit_excel",function(e)
        {

        e.preventDefault();
        let property = document.getElementById("file").files[0]                     
        if(property == undefined)
        {                            
           $("#u_errorDiv").addClass("show").children("span").text(`Please 
           select file`);
        }else
           {
             var image_name = property.name;
             var image_extension = image_name.split(".").pop().toLowerCase();                              
             if($.inArray(image_extension , ['xlsx','xls']) == -1)
               {                                      
                  $("#u_errorDiv").addClass("show").children("span")
                .text(`Caution :Only Excel files can be uploaded`);
              }else
                {                                        
                    var form_id = $("#u_excel_form");
                    var u_course = $("#u_subject_code").val();                                              
                    var formData = new FormData($('#u_excel_form').get(0));
                    formData.append("file",property);                                            
                    formData.append("course",u_course);                                            
                 formData.append($(this).attr('name'),$(this).attr('value'));


         $.ajax({
                url:"main.php?function=upload_excel",
                method:"POST",
                data:formData,
                contentType:false,
                cache:false,
                processData:false,
                beforeSend:function()
                  {
                    $("#u_errorDiv > span").removeClass("text-danger");

                    var query = `<i class="fas fa-spinner fa fa-spin "></i>`;                                                  

                     $("#u_errorDiv").addClass("show").children("span")
                    .html(`Questions are  uploading 
                      ${query}`).addClass('text-info');

                  },
                   success:function(data)
                    {
                      $("#u_errorDiv > span").removeClass("text-info");

                      data = JSON.parse(data);

                      if(data[0] == 1)
                       {
                         $("#u_errorDiv").addClass("show").children("span")
                         .text(`${data[1]}`).addClass('text-success');

                        $("#u_excel_form input").not("input:submit").val("");

                        $("#u_submit_excel").attr("disabled","disabled");

                  }else{

                        $("#u_errorDiv").addClass("show").children("span")
                       .text(`${data[1]}`).addClass('text-danger'); 


                },error:function(xhr, status, errorThrown)
                   {
                     alert( "Sorry, there was a problem!" );
                     console.log( "Error: " + errorThrown );
                     console.log( "Status: " + status );
                     console.dir( xhr );
                   },
                  cache:false
             });                            
         } 
       }
     });

php code to upload file onto database

      function fn_fetchExcelFileToServer() {
           GLOBAL $fname,$uploadOk,$conn;
           $msg = "";  
           $user_id = $_SESSION['user'];
           $status;
           $output = array();
           $subject_id;

           $subject_code = 
               $conn->real_escape_string(test_input($_POST['course']));
           $sql ="select course_id from course_detail where course_code = 
                    '".$subject_code."'";

       $result = $conn->query($sql);    

       if($result->num_rows != 0)
         {
              $subject_id = $result->fetch_assoc()['course_id'];            
              $target_dir = "ExcelFiles/";
              $actual_file_name = basename($_FILES["file"]["name"]);
              $FileType = pathinfo($actual_file_name,PATHINFO_EXTENSION);
              $target_file = $target_dir.uniqid($user_id).".".$FileType;

              if(strcmp($FileType, "xls")==0  ||  
                       strcmp($FileType,"xlsx")==0) 
              // Check if  file is a actual excel file not
                {   
                          $uploadOk = 1;
                } 
              else 
                {
                        $status = 0;
                        $msg.=" File is not Excel file. ";
                        $uploadOk = 0;
                }

              if (file_exists($target_file))  
                // Check if file already exists
                  {
                          $status = 0;
                          $msg.=" Sorry, file already exists. ";
                          $uploadOk = 0;
                  }

              if ($_FILES["file"]["size"] > 500000) 
                   // Check file size
                  {
                            $status = 0;
                            $msg.=" Sorry, file is too large. ";
                            $uploadOk = 0;
                  }

              if ($uploadOk == 0)                           
                  // Check if $uploadOk is set to 0 by an error
                 {
                     $status = 0;
                     $msg.= "Sorry, your file was not uploaded."; 
                  // if everything is ok, try to upload file
                 } 
              else
                  {
                    if (move_uploaded_file($_FILES["file"]["tmp_name"], 
                      $target_file))
                       {
                         $msg .= "The file ".basename( $_FILES["file"] 
                                  ["name"]). " has been uploaded.";
                            $fname = $target_file;

                            $stmt = $conn->prepare("insert into 
               uploaded_excel(teacher_id, excel_id, file_name) values(?, ?, 
              ?,)");        

                $stmt->bind_param("iss",$teacher,$excel_id,$file_name);

                            $teacher = $user_id;
                            $excel_id = $target_file;
                            $file_name = $actual_file_name;
                            $stmt->execute();
                            $stmt->close();

                            $status = 1;

                    } 
                   else
                       {
                            $status = 0;
                    $msg .= "Sorry, there was an error uploading your file.";
                       }
                 }



        }else{
               $status = 0;
                $msg .= "Please Verify Your Course Code ";
             }


       if($status == 1)
       {

           return $subject_id;

       }else{

                array_push($output,$status);
                array_push($output,$msg);
                print_r(json_encode($output));

                die();
            }

}

Error displayed is this :

            Uncaught SyntaxError: Unexpected token < in JSON at position 1
                  at JSON.parse (<anonymous>)
                  at Object.success (interfacejQuery.js:1137)
                  at u (jquery.min.js:2)
                  at Object.fireWith [as resolveWith] (jquery.min.js:2)
                  at k (jquery.min.js:2)
                  at XMLHttpRequest.<anonymous> (jquery.min.js:2)

and please tell me why every time i select a file it flips to no file selected

actual output should be files uploaded successfully


Viewing all articles
Browse latest Browse all 67441

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>