How to add $_SESSION variable into an Ajax Request and INSERT data into mysql database PHP?

280
September 05, 2017, at 1:00 PM

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\htdocs\reports\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!

Answer 1

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);
            }
        });
    }
Answer 2

Another method is to make an api that returns you the user ID.

Like: returnSessionId.php

echo $_SESSION['userSession'];

In your html:

function getCalendar(target_div,year,month){
    $.ajax({
        type:'POST',
        url:'returnSessionId.php',
        success:function(sessionID){
            console.log(sessionID);
        }
    });
}

This way you can get the ID where ever you want even if your script is not on the same page as you php file.

Answer 3

Have you session user id in calendar_div element as hidden with proper class or id. (i.e) input type hidden and place your session value. In addEvent click function you can get that session value using id/class and pass as ajax parameter.

It will solve your problem.

READ ALSO
div Overlay for every div in an array cont. (sort function error)

div Overlay for every div in an array cont. (sort function error)

Dam I'm gonna have to ask you to help me on another error

240
How to conditionally change the table th tag text content

How to conditionally change the table th tag text content

I am new to JavaScript & jQueryI want to conditionally change the th text based on the content of an array

190
How to append &lt;div&gt; content in jQuery

How to append <div> content in jQuery

How to append below code in jQuery to display dynamically

256
mySQL select query does not return results when using a WHERE clause against a NULL column.

mySQL select query does not return results when using a WHERE clause against a NULL column.

I have a single column in a table which looks like this:

222