PHP and SQL update table by specified row - php

I have a table pulling info from a database with the last column of each row being an input tag labeled COMPLETE a user can click on. I want to be able to click on the tag and have it update my database to change a boolean field which would change COMPLETE from 0 to 1. Right now, I can't seem to update the rows if I click on them out of order. so If i click to update the first row and then click a few rows below, it will update the second row. It will update any row you want if you click the button for that row twice, but first it updates the row where you left off previously...
<form action='' method='POST'>
<?php
$current_date = date("Y-m-d");
$n = 1;
$sql = "SELECT id, date, pname, details, time, tech FROM task WHERE task='LAB' AND complete=0 ORDER BY date DESC";
$result = $link->query($sql);
echo $current_date;
echo "<table>
<tr>
<th>Date</th>
<th>Project</th>
<th>Details</th>
<th>Start Time</th>
<th>Technician</th>
</tr>";
while ($row = $result->fetch_assoc()) {
echo "<tr align='center'><td>" .$row["date"]. "</td><td>" .$row["pname"]. "</td><td>"
.$row["details"]. "</td><td>" .$row["time"]. "</td><td>" .$row["tech"]. "</td>
<td><input type='submit' name=".$n." value='Complete' /></td></tr>";
if (isset($_POST[$n])) {
$id = $row["id"];
$update = "UPDATE task SET complete = 1 WHERE task='LAB' AND id = ".$id."";
echo $update;
$update_result = $link->query($update);
}
$n++;
}
echo "</table>";
$link->close();
?>
</form>

One of the things I noticed was you don't do proper concatenation.
ANSWER:
You can try putting form for each row, then use hidden input field for storing the id:
while ($row = $result->fetch_assoc()) {
echo '<tr align="center">
<td>'.$row["date"].'</td>
<td>'.$row["pname"].'</td>
<td>'.$row["details"].'</td>
<td>'.$row["time"].'</td>
<td>'.$row["tech"].'</td>
<td>
<form action="" method="POST">
<input type="hidden" name="id" value="'.$row["id"].'">
<input type="submit" name="complete" value="Complete"/>
</form>
</td>
</tr>';
}
You can then process the form:
if(isset($_POST["complete"])) {
$id = $_POST["id"];
$stmt = $link->prepare("UPDATE task SET complete = 1 WHERE task='LAB' AND id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->close();
}
Second Option:
You can try using Ajax for seamless transaction:
while ($row = $result->fetch_assoc()) {
echo '<tr align="center">
<td>'.$row["date"].'</td>
<td>'.$row["pname"].'</td>
<td>'.$row["details"].'</td>
<td>'.$row["time"].'</td>
<td>'.$row["tech"].'</td>
<td>
Complete
</td>
</tr>';
}
Then create your script (I'll be using jQuery for this example). You may include this at the bottom of your main file:
<script>
$(document).ready(function(){ /* PREPARE THE SCRIPT */
$(".btn").click(function(){ /* WHEN COMPLETE BUTTON IS CLICKED */
var elem = $(this),
id = elem.attr('data-artid'); /* GET THE ID OF THE CLICKED ELEMENT */
$.ajax({ /* PROCESS AJAX */
url: "process.php", /* THE FILE WHERE THE FORM WILL BE PROCESSED */
type: "POST", /* METHOD TO BE USED */
data: {"id":id}, /* THE DATA TO BE PASSED TO process.php */
dataType: 'json', /* TYPE OF DATA TO BE RETURNED */
success: function(result){ /* IF process.php IS SUCCESSFUL */
if(result.boolean){
elem.closest('tr').remove(); /* REMOVE THE ENTIRE ROW */
}
}
});
return false; /* THIS WILL PREVENT FROM SCROLLING TO THE TOP OF THE PAGE */
});
});
</script>
Then process the form in process.php (separate file):
/** INCLUDE HERE SOMEWHERE YOUR DATABASE CONNECTION **/
$boolean = false; /** DEFAULT VALUE TO BE RETURNED **/
if(!empty($_POST["id"])){
$id = $_POST["id"];
$stmt = $link->prepare("UPDATE task SET complete = 1 WHERE task='LAB' AND id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->close();
$boolean = true;
}
echo json_encode(array('boolean' => $boolean)); /* THIS WILL BE RETURNED TO THE AJAX REQUEST */

Related

Showing a sql table when radio button is selected using AJAX

I have a webpage with three radio buttons and an empty table. My goal is to select a radio button and have the table show a list of employees based on whichever radio button is clicked. Right now the list does not show up when I hit the button. I don't know what I'm doing wrong. I tried adding an alert to the doAjax function and the alert appeared so I know it's getting to that function. Below is my code, I have three files. Any help is appreciated.
//assign3.php
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src = "http://code.jquery.com/jquery-3.2.1.min.js">
</script>
<script src ="js/assign3js.js" type = "text/javascript" ></script>
</head>
<body>
<table border ='1'style = 'margin:auto' id = "employees" >
<tr><td colspan ='3'><h1>Employees </h1></td></tr>
<th> First Name</th>
<th>Last Name</th>
<th>Employee ID</th>
</table>
<input type="radio" name="employeeType" value="server" id="server"> Server<br>
<input type="radio" name="employeeType" value="bartender"id="bartender"> Bartender<br>
<input type="radio" name="employeeType" value="host"id = "hosts"> Host<br>
</body>
//script.js
$("document").ready(
function()
{
$("#server").click(doAjax);
$("#hosts").click(doAjax1);
$("#bartender").click(doAjax2);
}
);
function doAjax()
{
$.ajax({"method":"POST","url":"servers.php"}).done(update);
}
function update(data)
{
result = JSON.parse(data);
for(index =0; index < result.length; index++)
{
var row = "<tr>";
row += "<td>" + result[index].firstName + "</td>";
row += "<td>" + result[index].lastName + "</td>";
row += "<td>" + result[index].employeeID + "</td>";
row += "</tr>";
$("#employees").append(row);
}
}
//server.php
<?php
$server = (object) null;
$connection = "mysql:host=localhost;dbname=restaurant";
$user = "root";
$pwd = "mysql";
$db = new PDO($connection, $user, $pwd);
$results = $db->query("SELECT firstName, lastName, employeeID FROM
employee JOIN `server` ON employee.employeeID = server.employeeID");
while ($row = $results->fetch())
{
$server->firstName= $row["firstName"];
$server-> lastName=$row["lastName"] ;
$server->employeeId = $row["employeeID"];
}
$employee = [];
array_push($employee,$server);
$json1 = json_encode($employee);
echo $json1;
?>
My answer is just an addition to #alex's answer. Alex has very good pointed out the main problems/aspects!
I would suggest you another approach: to use only one js function for getting the employee data, no matter which radio button you are selecting. When you click on a radio button, send an ajax request with the corresponding radio button's value as argument. This value will be read on the server side and, dependent on it, a corresponding sql statement will be built and executed. The response will be read and appended to the employees table.
There would be too much to say here regarding your code version and my proposal. I hope you'll understand what I did.
Main points:
I renamed "server.php" to "get-employee.php" (it's obvious why).
I implemented the use of prepared statements instead of query, so that you are on a safe side in regard of the sql injection, in case you need to use input parameters in your queries.
The employee data is fetched from db and saved in an array by using the fetchAll() method. No need for fetching and looping through objects.
The db connection details are defined in constants.
An array with db connection options regarding exception handling and others is added now (needed).
Added the tbody container to the table, to which the employees data will be appended. In general, if you use th then use it inside a thead container. And if you use thead, then use a tbody too.
I think this is all that's important. Feel free to ask me anything... tomorrow.
Good luck further.
assign3js.js
$(document).ready(function () {
$('input[name="employeeType"]').click(function () {
var employeeType = $(this).val();
updateEmployees(employeeType);
});
});
function updateEmployees(type) {
$.ajax({
method: 'post',
dataType: 'json',
url: 'get-employee.php',
data: {
'type': type
}
})
.done(function (response, textStatus, jqXHR) {
if (response) {
for (var i = 0; i < response.length; i++) {
var row = '<tr>';
row += '<td>' + response[i].firstName + '</td>';
row += '<td>' + response[i].lastName + '</td>';
row += '<td>' + response[i].employeeID + '</td>';
row += '</tr>';
$('#employees tbody').append(row);
}
} else {
$('#employees tbody').append('<tr><td colspan="3">No employees found</td></tr>');
}
})
.fail(function (jqXHR, textStatus, errorThrown) {
// alert(textStatus + '\n' + errorThrown + '\n\n' + jqXHR.responseText);
})
.always(function (response, textStatus, jqXHR) {
//...
});
}
assign3.php:
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
<meta charset="UTF-8" />
<!-- The above 3 meta tags must come first in the head -->
<title>Demo</title>
<script src="http://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="js/assign3js.js" type="text/javascript"></script>
<style type="text/css">
#employees {
/*margin: auto;*/
border: 1px solid #ccc;
}
#employee-types {
margin-top: 20px;
border: 1px solid #ccc;
}
</style>
</head>
<body>
<table id="employees">
<thead>
<tr>
<th colspan="3">
<h1>Employees</h1>
</th>
</tr>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Employee ID</th>
</tr>
</thead>
<tbody></tbody>
</table>
<fieldset id="employee-types">
<legend>Employee type</legend>
<input type="radio" id="server" name="employeeType" value="server">
<label for="server">Server</label><br/>
<input type="radio" id="bartender" name="employeeType" value="bartender">
<label for="bartender">Bartender</label><br/>
<input type="radio" id="hosts" name="employeeType" value="host">
<label for="hosts">Host</label><br/>
</fieldset>
</body>
</html>
get-employee.php
<?php
// Db configs.
define('HOST', 'localhost');
define('PORT', 3306);
define('DATABASE', 'restaurant');
define('USERNAME', 'root');
define('PASSWORD', 'mysql');
define('CHARSET', 'utf8');
// Error reporting.
error_reporting(E_ALL);
ini_set('display_errors', 1); // SET IT TO 0 ON A LIVE SERVER!
//
// Create a PDO instance as db connection to db.
$connection = new PDO(
sprintf('mysql:host=%s;port=%s;dbname=%s;charset=%s', HOST, PORT, DATABASE, CHARSET)
, USERNAME
, PASSWORD
, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => FALSE,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]
);
$response = false;
if (isset($_POST['type'])) {
$employeeType = $_POST['type'];
/*
* The bindings array, mapping the named markers from the sql statement
* (if any) to the corresponding values. It will be directly passed as
* argument to the PDOStatement::execute method.
*
* #link http://php.net/manual/en/pdostatement.execute.php
*/
$bindings = [];
// Set the sql statement based on the submitted employee type.
switch ($employeeType) {
case 'bartender':
// $sql = '...';
// $bindings[:markerName] = markerValue;
break;
case 'hosts':
// $sql = '...';
// $bindings[:markerName] = markerValue;
break;
case 'server':
default:
$sql = 'SELECT
emp.firstName,
emp.lastName,
emp.employeeID
FROM employee AS emp
JOIN `server` AS srv ON srv.employeeID = emp.employeeID';
break;
}
// Prepare the sql statement for execution and return a statement object.
$statement = $connection->prepare($sql);
// Execute the prepared statement.
$statement->execute($bindings);
// Fetch data - all at once - and save it into response array.
$response = $statement->fetchAll(PDO::FETCH_ASSOC);
//-----------------------------------------------------------------------
// ...or fetch data one record at a time and save it into response array.
//-----------------------------------------------------------------------
// $employee = [];
// while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
// $employee[] = $row;
// }
// $response = $employee;
//-----------------------------------------------------------------------
}
echo json_encode($response);
Your SQL query is wrong, you have it doing
SELECT firstName, lastName, employeeID FROM employee JOIN `server` ON
employee.employeeID = server.employeeID
but employeeID exists in both employee and server so you need to modify your query to specific which table to get employeeID from so it should look like
SELECT employee.firstName, employee.lastName, employee.employeeID FROM employee JOIN `server` ON
employee.employeeID = server.employeeID
I made an SQLFiddle here which shows this. You should check if $results equals false, because the query function will return false if it fails.
That worked for me, I had to change line 14 in server.php as well or else it wouldn't display the employee ID, this was because in the ajax script you reference it as employeeID but you set it as employeeId on line 14 so it would now be
$server->employeeID = $row["employeeID"];
Now when you run all of it will only one employee, if you want it to return multiple you need to have an array in server.php that you push employees to because right now it will overwrite the previous employee and only return the last one because of them writing to the same object with the same keys.
For multiple employees to return I changed the code to
...
$server = [];
...
$count = 0;
while ($row = $results->fetch()) {
//create new class to stop warnings of creating object from empty value
$server[$count] = new \stdClass();
$server[$count]->firstName= $row["firstName"];
$server[$count]->lastName=$row["lastName"] ;
$server[$count]->employeeID = $row["employeeID"];
$count++;
}
...
what this does is $server is now an array, and every time we loop over an employee in the while loop we assign our values to a new object stored in $server's array.
and the script.js looked like this
function update(data) {
var result = JSON.parse(data)[0]; // [0] because the json was wrapped in
// double []'s
for(var index =0; index < result.length; index++) {
var row = "<tr>";
row += "<td>" + result[index].firstName + "</td>";
row += "<td>" + result[index].lastName + "</td>";
row += "<td>" + result[index].employeeID + "</td>";
row += "</tr>";
$("#employees").append(row);
}
}
Not sure if any of this is the best solution to the problem, but I got it to work without too much trouble.

While loop updation value

I am developing online attendance.But I stuck in while loop condition
I want to show my code first
<tbody>
<?php
$database = new Database();
$db = $database->getConnection();
$user = new User($db);
$stmt = $user->atten();
while($ro22 = $stmt->fetch(PDO::FETCH_ASSOC))
{
?>
<tr>
<td><input name ="uname" id ="uname" onBlur="checkAvailability2()" style ="border:none" value = "<?php echo $ro22['user_id'] ?>"/></td>
<td><?php echo $ro22['first_name'] ?> <?php echo $ro22['last_name'] ?></td>
<td><?php echo $ro22['parent_contact'] ?></td>
<td><input type="button" value="<?php echo $ro22['ai'] ?>" id="pres" name="pres" onclick="return change(this);" onBlur="checkAvailability()" class="w3-button w3-teal"/></td>
</tr>
<?php } ?>
</tbody>
This is output
What I want
I want update present,absent value based on 101,102,103... value
I tried many but failed. Please help me out
Thanks in advance
You need to place a call to the page on a click and pass the user_id. This is easy to do with jQuery:
function change(row) {
$.post('thispage.php', { user_id: $(row).val() }, function(){ window.location.reload(); } );
}
And then receive the post in the PHP:
if (!empty($_POST['user_id'])) {
/* toggle admission status */
}
After the request completes and the status is toggled, the page will reload.
Here is a general example. It's consisted of your PHP program (the AJAX sender) which I rewrote to be they way I think you wanted, a javascript file (containing the AJAX function) and another PHP file (the AJAX request receiver).
You can get different use-cases by altering the database query in the receiving PHP file.
Javascript file (AJAX):
// Send the `id` of the element
function checkAvailability(id)
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
// This `if` underneath is success. It means we got a response back
if (this.readyState == 4 && this.status == 200)
{
if(this.responseText == "OK")
{
alert('ID: ' + id + ' changed. Response: ' + this.responseText);
document.getElementById("demo").innerHTML = 'The student has been updated.';
}
else if(this.responseText == "Not OK")
{
alert('Something went wrong with id: ' + id);
}
}
};
// For example you send a request to attendance.php sending `id` info
// - attendance.php just needs to echo the response to answer back
xhttp.open("GET", "attendance.php?id=" + id, true);
xhttp.send();
}
Main PHP page (the file that sends the request):
// U need jQuery to be able to send AJAX requests. Copy this, add to your html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<?php
$database = new Database();
$db = $database->getConnection();
$user = new User($db);
$stmt = $user->atten();
echo '<table>
<tr>
<th>Student ID</th>
<th>Student name</th>
<th>Phone number</th>
<th>Today\'s attendance</th>
</tr>';
while($ro22 = $stmt->fetch(PDO::FETCH_ASSOC))
{
echo '<tr>
<td><input name ="uname" id ="uname" onBlur="checkAvailability2()" style ="border:none" value="'.$ro22['user_id'].'"/></td>
<td>'.$ro22['first_name'].' '.$ro22['last_name'].'</td>
<td>'.$ro22['parent_contact'].'</td>
<td><input type="button" value="'.$ro22['ai'].'" id="pres" name="pres" onclick="change(this.id);" onBlur="checkAvailability(this.id)" class="w3-button w3-teal"/></td>
</tr>';
}
echo '</table>';
?>
The receiver file:
<?php
$conToDatabase = ... // Here goes DB connection data
if(isset($_GET['id']) && ctype_digit($_GET['id']))
{
$clean['id'] = $_GET['id'];
}
// Query your DB here using variable $clean['id'] as ID
$querySuccess = ...
// if query successful echo 'OK';
// else echo 'Not OK';
?>

insert value of select form into mysql

I have a form that adds vehicles to a database, there are 2 drop down select fields in the form, 'Make' and 'Model'
When I select an option from either one to insert it into the stock table in the database the make 'ID' or model 'ID' gets inserted into vehicle make / model rather than the name of the vehicle make, so '3' gets inserted instead of 'Volkswagen'
Here is some of my code
<form action="addstock.php" method="post" enctype="multipart/form-data">
<div class="make">
<div id="field1">Make:</div> <div id="field2">
<select name="mke" id="mke">
<?php
include 'includes/db2.php';
$SQL = "SELECT * FROM make";
$query = mysqli_query($con, $SQL);
while ($row = mysqli_fetch_array($query)) {
$res = "<option ";
$res .= "value='".$row['code']."'>";
$res .= $row['vehicle_make'];
$res .= '</option>';
echo $res;
}
?>
</select>
</div>
</div>
</div>
<script src="jquery/jquery-2.1.4.min.js"></script>
<script>
$(document).ready(function(){
$('#mke').change(function(){
var code = $(this).val();
var data = 'code='+code;
$.ajax({
type : "POST",
url : "fill.php",
data : data,
cache: false,
success: function(html)
{
$('#mdl').html(html);
}
});
});
});
</script>
Code for the model drop down option, the rest of the code for this is on another page (fill.php)
<div id="field1">Model:</div> <div id="field2">
<select name="mdl" id="mdl">
<option selected="selected">Model</option>
</select>
</div>
</div>
fill.php page
if(isset($_POST['code']))
{
$SQL = "SELECT * FROM model WHERE MakeCode = '".$_POST['code']."'";
$query = mysqli_query($con, $SQL);
if(mysqli_num_rows($query) == 0 )
{
echo '<option>No Results</option>';
} else {
while ($row = mysqli_fetch_array($query)) {
$res = "<option ";
$res .= "value='".$row['id']."' >";
$res .= $row['vehicle_model'];
$res .= "</option>";
echo $res;
}
}
} else {
echo '<option >error</option>';
}
?>
Back on the addstock.php page here is the insert code
<?php
if(isset($_POST['addstock'])){
$mke = $_POST['mke'];
$mdl = $_POST['mdl'];
$addstock = "insert into stock (veh_make,veh_model) values('$mke','$mdl')";
$addsto = mysqli_query($con, $addstock);
if($addsto){
echo "<script>alert('Vehicle has been added')</script>";
echo "<script>window.open('addstock.php','_self')</script>";
}
}
I'm fairly new to php and not sure how to insert the name instead of the id, as when I am trying to display a vehicle on another page the ID's show like 3 4, instead of Volkswagen Golf
Hope you understand what I mean
Any help is much appreciated!
You can insert the result of a SELECT statement that gets you the make and model:
"insert into stock (veh_make,veh_model) select make.vehicle_make, vehicle_model FROM make, model WHERE make.id=$mke AND model.id=$mdl"
But this is wrong DB design. stock should not contain make and model names, but rather IDs, references to rows in other tables, or Foreign Keys.

Is it possible to return a table with some constraint in another .php page in ajax and show it in div

when i click the today button, it goes to updatetoday.php page where i select a query and display it in call back of an ajax and display the table in .php file to div with id #test. but it display's error as Uncaught TypeError: Illegal invocation
$(document).ready(function(){
$('#today').click(function()
{
alert("hi");
$.ajax({
url:'updatetoday.php',
data:{update:today}, // pass data
success:function(result)
{$( "#test" ).html(result);}
});
});
});
updatetoday.php
<?php
$conn = mysql_connect('localhost', 'root', 'root') or die("error connecting1...");
mysql_select_db("cubitoindemo",$conn) or die("error connecting database...");
if($_GET['update']==today) //taking
{
echo "<table align='center' border='1' cellspacing='2'><tr><th>Book_id</th><th>Name</th><th>Phone Number</th><th>Email Address</th><th>Start Date</th><th>Source</th><th>Destination</th><th>Morning Time</th><th>Evening Time</th><th>Duration</th><th>Days Off</th><th>Date Off</th><th>Current Status</th><th>Call Counter</th><th>Option</th><th>Calender</th><th>Save</th></tr><br><br><br>
<?php
$query_book = 'Select * from `booking` where validity = 1 limit 5';
$result_book = mysql_query($query_book);
while($row = mysql_fetch_assoc($result_book))
{
$user_id = $row['user_id'];
// query for customer table
$query_cus = 'Select * from `customer` where user_id = $user_id limit 5';
$result_cus = mysql_query($query_cus);
$row_cus = mysql_fetch_assoc($result_cus);
$name = $row_cus['user_id'];
$email = $row_cus['email_id'];
$mobile_number = $row_cus['mobile_number'];
$current_status = $row['valid'];
$startdate = $row['start_date_timestamp'];
if($current_status == '1')
{
$status = '<p style='color:green;font-weight:600;font-size:19px'>Reg</p>';
}
else if($current_status == '2')
{
$status = '<p style='color:green;font-weight:600;font-size:19px'>New</p>';
}
else if ($current_status == '3.1' )
{
$status = '<p style='color:red;font-weight:600;font-size:19px'>R</p>';
}
?>
<tr align='center'><td class='bookid'><?=$row['book_id']?></td><td ><?=$row_cus['name']?></td><td ><?=$row_cus['mobile_number']?></td><td ><?=$row_cus['email_id']?></td><td><?=$row['start_date_timestamp']?></td><td ><?=$row['source']?></td><td ><?=$row['destination']?></td><td ><?=$row['mor_timestamp']?></td>
<td><?=$row['eve_timestamp']?></td><td><?=$row['duration']?></td><td ><?=$row['days_off']?></td><td ><?=$row['date_off']?></td>
<td><?=$row['current_status']?></td ><td ><?=$row['call_counter']?></td>
<td><select class='sel' name='select_option'><option value='NULL'>Select An Option</option><option value='taking'>Taking</option><option value='later-def'>Later Defined</option><option value='later-undef'>Later Undefined</option><option value='outofrange'>Out Of Range</option><option value='rejected'>Rejected</option><option value='norespond'>No Respond</option></select></td><td><input type='text' class='cal' size='6' disabled='disabled' value='<?=$startdate?>'/></td><td><button id='<?php echo $row['book_id'];?>' class='save'>Save</button></td></tr>
<?php
}//booking table while ends
echo '</table>';
?>
</div>";
}
?>
To fix your problem you must change the line :
data:{update:today}, // pass data
to :
data:{update:'today'}, // pass data
in your code today is a string not a varible
Change the line :
success:function(data)
to :
success:function(result)
You are assigning the result from the php to a variable called data and in
{$( "#test" ).html(result);}
trying to display inside the #test div a variable called result.

JavaScript variable value to PHP variable

I have a JavaScript function that creates a <div>. It uses Ajax to access the database so and creates a different <div> if the dates match. But now I want to take the 'date' variable from the JavaScript <div> that matches the database and send it through another PHP function that gets all entries with that date and echoes them out to a JQuery pop-up. What am I’m doing wrong and is there an easier way than the code below?
First AJAX call:
beforeMonth:function(date)
{
$.ajax({
type: "GET",
url: "getCalendarEvents.php",
dataType: "json",
data: "date="+date,
async: false, //stop rendering the calender until eventdates is changed.
success: function(json){
$.fn.ical.changeEventDates(json); //this function changes the eventdates
}
})
}
getCalendarEvents.php
include ("Includes/dbConnect.php");
$_GET['date'];
$query2 = "SELECT * FROM events";
$checkevent = mysqli_query($cxn,$query2) or die("Couldn't execute query!");
$dates = array();
while ($row2 = mysqli_fetch_array($checkevent))
{
$eventDate = $row2['eventDate'];
$eventName = $row2['eventName'];
$eventHost = $row2['host'];
$dates[$eventDate] = array('title' => $eventName, 'desc' => $eventHost);
}
echo json_encode(array("dates" => $dates));
exit;
JavaScript in a separate file (just the function that creates the <div>):
if(!datejson)
{
options.beforeDay(formatdate);
$("table tr:last, obj").append("<td id = '"+formatdate+"'>"+i+"</td"); //add day
}
else
{
options.beforeDay(formatdate);
$("table tr:last, obj").append("<td class='date_has_event' id = '"+formatdate+"' name='"+formatdate+"'>"+i+"<div class='title'><a href='#' class='popup'><img src='images/facebook.png' class='popup'/></a></div>"+"<div class='events'><ul><li><span class='desc'>"+datejson.desc+"</span></li></ul></div></td"); //add day
}
PHP in the HTML:
<div id="popupContact">
Close X
<div id="popupHeader">Events occurring on</div>
<?php
include ("Includes/dbConnect.php");
$calendarDate=$_GET['formatdate']
$query = "SELECT * FROM events WHERE eventDate='$calendarDate'";
$check = mysqli_query($cxn,$query) or die("Couldn't execute query!");
while($row = mysqli_fetch_array($check))
{
$id = $row['eventID'];
echo "<div class='submit_event_list'><a href='individual_event_page_main.php?id=$id'>";
echo $row['eventName'];
echo " | " . $row['venue'];
echo " | " . $row['eventDate'];
echo "</a></div>";
echo "<br />";
}
mysqli_close($cxn);
?>
</div>

Categories