dscuu86620 2017-09-05 04:31
浏览 96
已采纳

如何将$ _SESSION变量添加到Ajax请求中并将数据插入到mysql数据库PHP中?

I'm just beginning in web development and I am trying some stuff in PHP with Ajax. I recently downloaded a script which uses php,jquery and ajax. What it does is that it shows a calendar which enables input once a user clicks a particular day and add the data to the database once the user clicks the 'Add' button.

It looks somethings like this

Afterwards, I modified the database table wherein I added a user_id as a column because I wanted the calendar daily report to be viewed only by the user who adds data into it. Now, my problem is that I cannot use my $_SESSION['userSession'] into the Ajax request. I tried to add the variable into the mysqli queries but unfortunately, it produces this kind of error:

Notice: Undefined variable: u_id in C:\xampp\htdocseports\functions.php on line 288

I have two PHP files, One for the main page and the other one for processing the calendar and other functions for the calendar.

Here is what my reports.php file looks like:

 <?php
session_start();
include_once 'dbconnect.php';
include_once('functions.php');

if (!isset($_SESSION['userSession'])) {
    header("Location: index.php");
}

$query = $DBcon->query("SELECT * FROM users WHERE user_id=".$_SESSION['userSession']);
$userRow=$query->fetch_array();
$DBcon->close();

$u_id = $_SESSION['userSession']; //this  is the variable that I am trying to pass to the functions.php file

    ?>
<!-- The echo below produces the calendar view -->
<div id="calendar_div">
    <?php echo getCalender(); ?>
</div>

Now here is the sample of functions.php:

<?php


if(isset($_POST['func']) && !empty($_POST['func'])){
    switch($_POST['func']){
        case 'getCalender':
            getCalender($_POST['year'],$_POST['month']);
            break;
        case 'getEvents':
            getEvents($_POST['date']);
            break;
        //For Add Event
        case 'addEvent':
            addEvent($_POST['date'],$_POST['title'],$_POST['week'],$_POST['hours']);
            break;
        default:
            break;
    }
}

?>



<script type="text/javascript">
    function getCalendar(target_div,year,month){
        $.ajax({
            type:'POST',
            url:'functions.php',
            data:'func=getCalender&year='+year+'&month='+month,
            success:function(html){
                $('#'+target_div).html(html);
            }
        });
    }

    function getEvents(date){
        $.ajax({
            type:'POST',
            url:'functions.php',
            data:'func=getEvents&date='+date,
            success:function(html){
                $('#event_list').html(html);
                $('#event_add').slideUp('slow');
                $('#event_list').slideDown('slow');
            }
        });
    }
    //For Add Event
    function addEvent(date){

        $('#eventDate').val(date);
        $('#eventDateView').html(date);
        $('#event_list').slideUp('slow');
        $('#event_add').slideDown('slow');
    }
    //For Add Event
    $(document).ready(function(){
        $('#addEventBtn').on('click',function(){
            var date = $('#eventDate').val();
            var title = $('#eventTitle').val();
            var week = $('#eventWeek').val();
            var hours = $('#eventHours').val();
            $.ajax({
                type:'POST',
                url:'functions.php',
                data:'func=addEvent&date='+date+'&title='+title+'&week='+week+'&hours='+hours,
                success:function(msg){
                    if(msg == 'ok'){
                        var dateSplit = date.split("-");
                        $('#eventTitle').val('');
                        $('#eventWeek').val('');
                        $('#eventHours').val('');
                        alert('Daily report has been added.');
                        getCalendar('calendar_div',dateSplit[0],dateSplit[1]);
                    }else{
                        alert('Some problem occurred, please try again.');
                    }
                }
            });
        });
    });

function getEvents($date = ''){
    //Include db configuration file
    include 'dbconnect.php';
    $eventListHTML = '';
    $date = $date?$date:date("Y-m-d");
    //Get events based on the current date
    $result = $DBcon->query("SELECT title,hours FROM ojt_student_report WHERE date = '".$date."' AND status = 1 and user_id = '"$u_id"'");

    if($result->num_rows > 0){

        $eventListHTML = '<h2>Daily Report on '.date("l, d M Y",strtotime($date)).'</h2>';
        $eventListHTML .= '<ul class="list-group">';
        while($row = $result->fetch_assoc()){ 
            $eventListHTML .= '<li class="list-group-item"> <b>Daily Report:  </b><br>'.nl2br($row['title']). '<br>  <b>Working Hours: </b>' .$row['hours']. '</li>';
        }
        $eventListHTML .= '</ul>';

    }
    echo $eventListHTML;
}

/*
 * Add event to date
 */
function addEvent($date,$title,$week,$hours){
    //Include db configuration file
    include 'dbconnect.php';
    $currentDate = date("Y-m-d H:i:s");
    //Insert the event data into database 
    $insert = $DBcon->query("INSERT INTO ojt_student_report (title,date,week,hours,created,modified,user_id) VALUES ('".$title."','".$date."','".$week."','".$hours."','".$currentDate."','".$currentDate."','"$u_id"')");
    if($insert){
        echo 'ok';
    }else{
        echo 'err';
    }
}
?>

Basically, what I just wanted to do is to have different calendar and daily reports view for each user using the $_SESSION variable. I hope I was able to state my problem properly, any help will be appreciated. Thank you very much!

  • 写回答

3条回答 默认 最新

  • duanjing7459 2017-09-05 04:35
    关注

    Try something like below code:

    function getCalendar(target_div,year,month){
            $.ajax({
                type:'POST',
                url:'functions.php',
                data:'func=getCalender&year='+year+'&month='+month + '&uid=<?php echo $u_id ; ?>',
                success:function(html){
                    $('#'+target_div).html(html);
                }
            });
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题