I have problem with my PHP AJAX code for uploading file. At first, it works fine then after a few months and reinstallation of my wampp server the code produces an error

Error: Undefine variable ls_no, ch_no, grp_co, browser

Heres the code that I wrote

// upload_file.php

<?php
include_once("db_connect.php");

    $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    $id = substr(str_shuffle($chars),0,8);

    $ch_num = $_POST['ch_no'];
    $ls_num = $_POST['ls_no'];
    $lesson_desc = $_POST['brief_sum'];

    $filename = $_FILES['browse']['name'];
    $filename = mt_rand(10000,99999)."_".$filename;
    $temp_filename = $_FILES['browse']['tmp_name'];
    $file_type = $_FILES['browse']['type'];
    $file_size = $_FILES['browse']['size'];
    $file_error = $_FILES['browse']['error'];

            $date_month = date("m");
            $date_d = date("d");

            $date_year = date("Y");

            $hrs = date("h");
            $hrs = $hrs + 9;    
            $min = date("i");

            if($date_d > 1 ){
                $date_d = $date_d - 1;
            }
            $date = sprintf("%02d/%02d/%04d",$date_month,$date_d,$date_year);

    $path = "C:/wamp/www/site/elearning/lesson/$filename";

    if(strlen($lesson_desc) < 1){
        $lesson_desc = "No description";    
    }

    if(!$temp_filename){
        echo "No file selected, please upload again";
    }

    $sql = "SELECT * FROM tbl_lesson WHERE file_name='".$filename."'";
    $query = mysqli_query($cn,$sql);

    if(!(mysqli_num_rows($query) > 0)){

        $sql = "INSERT into tbl_lesson(id_no,date,ch_code,ls_code,file_name,file_size,file_path,description)
            VALUES('".$id."','".$date."','".$ch_num."','".$ls_num."','".$filename."','".$file_size."',
            '".$path."','".$lesson_desc."')";
            mysqli_query($cn,$sql);

    }else{
        exit(); 
    }
    if(move_uploaded_file($temp_filename,"C:/wamp/www/site/elearning/lesson/$filename")){
        echo("Upload Complete");    
    }


?>

upload_file.js

// JavaScript Document

$(document).ready(function(){
    $("#pg_bar").hide();
    $("#lbl_error_chapter").hide();
    $("#lbl_error_lesson").hide();
    $("#lbl_error_sum").hide();
    $("#lbl_successfull").hide();
    $("#lbl_error_txtchapter").hide();
    $("#lbl_error_txtlesson").hide();
    $("#lbl_err_file").hide();
    $(".hidden").hide();


    $("#txt_chapter").keypress(function(){
        if($("#txt_chapter").val().length > 1){
            $("#lbl_error_txtchapter").hide();
            $("#txt_chapter").css("border-color","DodgerBlue"); 
        }   
    });
    $("#txt_lesson").keypress(function(){
        if($("#txt_lesson").val().length > 1){
            $("#lbl_error_txtlesson").hide();
            $("#txt_lesson").css("border-color","DodgerBlue");  
        }       
    });
    $("#sl_chapter").change(function(){
            $("#lbl_error_chapter").hide();
            $("#sl_chapter").css("border-color","DodgerBlue");  
    });
    $("#sl_lesson").change(function(){
            $("#lbl_error_lesson").hide();
            $("#sl_lesson").css("border-color","DodgerBlue");   
    });
    $("#file_browser").change(function(){
            $("#lbl_err_file").hide();
            $("#file_browser").css("border-color","DodgerBlue");    
    });

});


function _(el){
    return document.getElementById(el); 
}
function uploadfile(){

    var ch_n = document.getElementById('sl_chapter').value;
    var ls_n = document.getElementById('sl_lesson').value;
    var grp_id = document.getElementById('grp_code').text;
    var txtch = $("#txt_chapter").val();
    var txtls = $("#txt_lesson").val();
    var file = document.getElementById('file_browser').value;
    var d = $("#txtarea_sum").val();
    var ppt = "application/vnd.ms-powerpoint";
    var pptx = "application/vnd.openxmlformats-officedocument.presentationml.presentation";
    var docx = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
    var pdf = "application/pdf";
    var avi = "video/x-msvideovideo/x-msvideo";
    var mp4 = "video/mp4";

    if(ch_n == "0"){
        $("#lbl_error_chapter").show();
        $("#sl_chapter").css("border-color","#F00");    
    }else{
        $("#lbl_error_chapter").hide();
        $("#sl_chapter").css("border-color","DodgerBlue");  
    }
    if(ls_n == "0"){
        $("#lbl_error_lesson").show();
        $("#sl_lesson").css("border-color","#F00"); 
    }else{
        $("#lbl_error_lesson").hide();
        $("#sl_lesson").css("border-color","DodgerBlue");       
    }
    if(txtch == ""){
        $("#lbl_error_txtchapter").show();
        $("#txt_chapter").css("border-color","#F00");   
    }
    if(txtls == ""){
        $("#lbl_error_txtlesson").show();
        $("#txt_lesson").css("border-color","#F00");    
    }
    if(file == ""){
        $("#lbl_err_file").show();
    }

    if(!(file == "") && !(ch_n == "0") && !(ls_n == "0") && !(txtch == "") && !(txtls == "")){
        var file = _("file_browser").files[0];

        if((file.type == ppt) || (file.type == pptx) || (file.type == docx) || (file.type == pdf) || (file.type == avi) || (file.type == mp4)){

            $("#lbl_err_file").hide();

            var formData = new FormData();
            formData.append("browse",file);
            formData.append("grp_co",grp_id);
            formData.append("ch_no",ch_n+": "+txtch);
            formData.append("ls_no",ls_n+": "+txtls);
            formData.append("brief_sum",d);
                var ajax = new XMLHttpRequest();
                ajax.upload.addEventListener("progress",progressHandler,false);
                ajax.addEventListener("load",completeHandler,false);
                ajax.addEventListener("error",errorHandler,false);
                ajax.addEventListener("abort",abortHandler,false);
                ajax.open("POST","includes/upload_file.php");
                ajax.send(formData);
                $("#pg_bar").show();    


        }else{

            $("#lbl_err_file").show();
            $("#lbl_err_file").html("Invalid file. Only files with (.ppt | .pptx | .docx | .pdf | .avi | .mp4 | .flv)       extensions are valid for uploading");

        } // END chech file type



    }

}
function progressHandler(e){
    _("total_size_upl").innerHTML = e.loaded+ "B / " + e.total + "B";
    var p = (e.loaded / e.total) * 100;
    _("pg_bar").value = Math.round(p) ;
    _("pg_val").innerHTML = Math.round(p) + "%";

    $("#btn_upload_lesson").attr("disabled","disabled");
    $("#file_browser").attr("disabled","disabled"); 
    $("#sl_chapter").attr("disabled","disabled");
    $("#sl_lesson").attr("disabled","disabled");    
    $("#txt_chapter").attr("disabled","disabled");
    $("#txt_lesson").attr("disabled","disabled");   
    $("#txtarea_sum").attr("disabled","disabled");
}
function completeHandler(e){
    var p = 0;
    _("pg_val").innerHTML = e.target.responseText;
    _("pg_bar").value = Math.round(p);

    setTimeout(function(){
                $("#lbl_successfull").show();
        },100);
    setTimeout(function(){
                window.location.href="upload-lesson.php";
        },2000);

}
function errorHandler(e){
    _("pg_val").innerHTML = "Upload failed";
}
function abortHandler(e){
    _("pg_val").innerHTML = "Upload failed";
}




html file


<?php
session_start();

    if(isset($_SESSION['username'])){

        $user_id = $_SESSION['ID'];
        $user_fname = $_SESSION['Firstname'];
        $user_Mname = $_SESSION['Middlename'];
        $user_Lname = $_SESSION['Lastname'];
        $user_position = $_SESSION['position'];
        $c = $_SESSION['grp_code'];

    }else{
        header("Location:index.php");   
    }

?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link href="_STYLES/page_layout.css" rel="stylesheet" type="text/css" /> <title>Upload Lesson</title> <link href="_STYLES/style_admin/upload-lesson.css" rel="stylesheet" type="text/css" /> <script src="_SCRIPTS/jquery-1.11.2.js"></script> <script src="_SCRIPTS/upload_lesson.js"></script> </head> <body> <div id="container"> <div id="header"></div> <div id="main_content"> <div id="tab_content"> <form id="upl_lesson" enctype="multipart/form-data" method="post"> <label class="headers">Fill up the form about the lessons to be uploaded</label> <p class="p_headers2">The system will only accept powerpoint presentation or files 
        with <strong>.docx | .pdf | .avi | .mp4 | .flv</strong> extensions for the lesson to be uploaded. Also, please make sure that you fill up the form correctly.
        </p> <label id="lbl_successfull">Lesson has been successfully uploaded !!</label> <a class="hidden" name="grp_co" id="grp_code"><?php echo $c;?></a> <a class="hidden" name="id" id="uid"><?php echo $user_id; ?></a> <select id="sl_chapter" name="ch_no"> <option value="0"> -- Select Chapter --</option> <option value="Chapter 1"> Chapter 1</option> <option value="Chapter 2"> Chapter 2</option> <option value="Chapter 3"> Chapter 3</option> <option value="Chapter 4"> Chapter 4</option> <option value="Chapter 5"> Chapter 5</option> <option value="Chapter 6"> Chapter 6</option> <option value="Chapter 7"> Chapter 7</option> <option value="Chapter 8"> Chapter 8</option> <option value="Chapter 9"> Chapter 9</option> <option value="Chapter 10"> Chapter 10</option> </select> <label id="lbl_error_chapter">Sorry you have inputted an invalid chapter.</label> <input type="text" placeholder="Type the chapter name" id="txt_chapter" name="chap_name" /> <label id="lbl_error_txtchapter">Invalid chapter name .</label> <select id="sl_lesson" name="ls_no"> <option value="0"> -- Select Lesson --</option> <option value="Lesson 1"> Lesson 1</option> <option value="Lesson 2"> Lesson 2</option> <option value="Lesson 3"> Lesson 3</option> <option value="Lesson 4"> Lesson 4</option> <option value="Lesson 5"> Lesson 5</option> <option value="Lesson 6"> Lesson 6</option> <option value="Lesson 7"> Lesson 7</option> <option value="Lesson 8"> Lesson 8</option> <option value="Lesson 9"> Lesson 9</option> <option value="Lesson 10"> Lesson 10</option> </select> <label id="lbl_error_lesson">Sorry you have inputted an invalid lesson number.</label> <input type="text" placeholder="Type the lesson name" id="txt_lesson" name="lessn_name" /> <label id="lbl_error_txtlesson">Invalid lesson name .</label> <textarea placeholder="Type the brief information of the lesson to be uploaded" id="txtarea_sum" name="brief_sum">
Member Avatar for diafol

Issues:

1. SQL
$sql = "INSERT into tbl_lesson(id_no,date,ch_code,ls_code,file_name,file_size,file_path,description)
        VALUES('".$id."','".$date."','".$ch_num."','".$ls_num."','".$filename."','".$file_size."',
        '".$path."','".$lesson_desc."')";
        mysqli_query($cn,$sql);

This is a bit of a mess. See DW Tutorial: Common Issues with MySQL and PHP #Item 4. Also, it appears that you're using raw input directly into your SQL ( $ch_num = $_POST['ch_no'];). This is asking for trouble with regard to SQL Injection. See the same link above #Item 2.

2. Date Calculation and Format

This looks like a lot of work. You can do just this:

$date = new DateTime();
$dateString = $date->modify("+9 hours")->format("Y-m-d");

Note the "UNIX" format, e.g. 2015-10-18. While you can certainly store other formats, they are particularly useless at being sorted in a DB table. Most developers stick to this "Y-m-d" format. Reformatting in PHP on echoing data is trivial.

3. Random Index

Not saying this is wrong. Just don't understand it. Why do you need this to be random? If it is a vanity thing, to not want to start on 1, you can set the incrementer to start on 450,000 - or anything you want.

4. Filename

Again, this is not wrong. Maybe attaching a microtime would be easier than the mt_rand()? It can be useful to notice the order of versions of the same file at a glance.

5. Error Checking

There is no error checking for the file upload 'error' item. You should check to see whether the upload is error-free before continuing with the "save". You do this: $file_error = $_FILES['browse']['error']; but then do nothing with it.

Sorry but your original question based around these variables:

Error: Undefine variable ls_no, ch_no, grp_co, browser

Where exactly in the code is that error being triggered? Is it here:

$ch_num = $_POST['ch_no'];
$ls_num = $_POST['ls_no'];
$lesson_desc = $_POST['brief_sum'];
$filename = $_FILES['browse']['name'];

If so, that wasn't the error message you saw, was it?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.