PHP populated FullCalendar, looks right, but data wont show - javascript

I am using mySQL to store information about check-out dates, and then depending on the object I would like to display the times that are already taken with FullCalendar.js
I am using PHP to pull in rows and then loop through them populating the where events are created, the code looks right when I check it on the page, but data is not loaded.
Here is the code generating the page:
function getAllTimes(){
if(!empty($_GET['id']))
{
$query = "
SELECT userID, startDate, endDate
FROM checkout
Where equID =" .$_GET['id'];
global $db;
$stmt = $db->prepare($query);
$stmt->execute();
$rows = $stmt->fetchAll();
echo "<script type=\"text/javascript\">
$(document).ready(function() {
$('#calendar').fullCalendar({
events: [";
$counter = 0;
foreach($rows as $row):
if($counter == 0)
{
echo "
{
title : '".$row['userID']."',
start : '".$row['startDate']."',
end : '".$row['endDate']."'
}";
$counter = $counter+1;
}
else
{
echo ",
{
title : '".$row['userID'].",'
start : '".$row['startDate'].",'
end : '".$row['endDate']."'
}";
$counter = $counter+1;
}
endforeach;
echo "
]
});
}}";
echo "
</script>";
}
else
echo "ID must be specified";
}
getAllTimes();
And this is the outcome when loaded, yet events are not added to the calendar.
<script type="text/javascript">
$(document).ready(function() {
$('#calendar').fullCalendar({
events: [
{
title : 'ArtemBeer',
start : '2014-01-16 00:00:00',
end : '2014-01-16 00:00:00'
},
{
title : 'ArtemBeer,'
start : '2014-01-15 00:00:00,'
end : '2014-01-16 00:00:00'
},
{
title : 'ArtemBeer,'
start : '2014-01-09 02:02:00,'
end : '2014-01-10 03:03:00'
}
]
});
}}
</script>

Your data (JS) has a bad comma:
start : '2014-01-15 00:00:00,'
should be:
start : '2014-01-15 00:00:00',
Also use your Chrome Inspector to see JS errors via the console, otherwise you will be guessing all day long.

Related

AJAX won't call the PHP file when using $.post()

I have been trying to export a search result to an Excel file (type .xls), before this, I have been using purely PHP and it works.
However, my client requests to have "live search" effect, so I have to shift to AJAX.
Here is the starting point: User clicks "Export" button, and in the javascript (in the main php file viewdata.php):
<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js'></script>
....
$(document).ready(function () {
var guid = <?php echo $guid ?>;
var date = document.getElementById("cbXDate").value;
var key = document.getElementById("cbsearch").value;
console.log("GUID: '" + guid + "', Date: '" + date + "' Key: '" + key + "'");
$.post("export_contacts.php",
{ sGuid: guid, sDate: date, sKey: key },
function () { console.log("Complete"); } );
});
cbXDate is an input field of type date to let user choose a date from whence to export the data, and cbsearch is a text input field to include a search keyword. console commands are added to see where the code execution has went through.
in the export_contact.php:
<?php
echo '<script> console.log("Export PHP activated."); </script>';
?>
I removed the PHP MySQL data selection code just to debug the problem (full source code below).
Problem is: export_contacts.php is never called. The "Export PHP activated" message never popped up in the console. The console only displayed the data values and "Completed", i.e. export_contacts.php was never called.
Output:
GUID: '0001', Date: '2021-08-01' Key: 'Jo'
Complete
Out of curiosity, I replaced $.post(...) with $("#export_div").load(...) and the console message showed up:
$(document).ready(function () {
var guid = <?php echo $guid ?>;
var date = document.getElementById("cbXDate").value;
var key = document.getElementById("cbsearch").value;
console.log("GUID: '" + guid + "', Date: '" + date + "' Key: '" + key + "'");
$("#export_div").load("export_contacts.php",
{ sGuid: guid, sDate: date, sKey: key },
function () { console.log("Complete"); } );
});
Output:
GUID: '0001', Date: '2021-08-01' Key: 'Jo'
Export PHP activated.
Complete
But this is not what I want, I want to write the output to a file, not display them in a div in the webpage. However, the data shown in the "export_div" div is correct, but the header part is not running, I know the quirkyness in header() calls, but I didn't output anything before the header() calls (unless output from the calling viewdata.php file also count?), here is the full export_contacts.php source code:
<?php
include("./php/auth.php");
$guid = $_POST['sGuid'];
$date = $_POST['sDate'];
$skey = $_POST['sKey'];
$searchKey = $_POST['sKey'];
if($searchKey == "")
{
$skey = "'%'";
}
else
{
$skey = "'%".$searchKey."%'";
}
$sql = "SELECT *, FROM_UNIXTIME(ROUND((date / 1000), 0) + 46800) AS date
FROM contacts
WHERE owner = '$guid' AND contact <> ''
AND (contact LIKE $skey OR name LIKE $skey) ";
if(!empty($date))
{
"AND date >= '$date' ";
}
$sql .= "ORDER BY contact;";
if($result = mysqli_query($link, $sql))
{
$columnHeader = '';
$columnHeader = "Owner" . "\t" . "Contact" . "\t" . "Name" . "\t" . "SaveDate" . "\t";
$setData = '';
while($rows = mysqli_fetch_assoc($result))
{
$rowData = '';
foreach ($rows as $value)
{
$value = '"' . $value . '"' . "\t";
$rowData .= $value;
}
$setData .= trim($rowData) . "\n";
}
// in case of .load() used,
// code works up until this point
// code doesn't work since here...
header("Content-type: application/xls");
header("Content-Disposition: attachment; filename=contact_".$guid.".xls");
header("Pragma: no-cache");
header("Expires: 0");
echo ucwords($columnHeader) . "\n" . $setData . "\n";
// until here
// this will show in console in case of .load() used
echo '<script> console.log("Export PHP activated."); </script>';
die();
}
else
{
echo "<script>window.alert('ERROR: '".mysqli_error($link).")</script>";
}
include("./php/cleanup.php");
?>
This code is working in the pure PHP version. I don't know why this header() part isn't working in here, could be due to its output got redirected to the div?
To make things clear, my question is: "Why $.post(...) isn't calling the PHP file, while $("#export_div").load(...) did?".
The header() part is just a sub question, and is fine if it's ignored.
As Kmoser pointed out, I was doing things wrong. None of the tutorial sites I visited did mention that $.post() will not return any result at all, while my php code is expecting the return of the search result and write them in a file in the header() calls.

Fullcalendar : Wrong end time displayed for events

I have an array of events which is here :
And this is my fullcalendar :
As you can see the end time is never the same as the array, but the start time is good, why?
What I have tried :
timezone : local
ignoreTimeZone : true
I didn't have effects on the rendering.
Note : the data is fetched in my database, the date are standard DATETIME format and it is json encoded in my php file.
I think it may be because I need to parse somehow my fields but I don't know how to do it.
this is my code :
$html .= '<div id="calendar"></div>';
// PROCEDURE SQL
$sql2 = "SELECT DISTINCT id, event_titre as 'titre', event_start as 'start', event_stop as 'stop' FROM tmp;";
//CALL WITH SESSION VARS
if(!$mysqli->query("CALL diff('". $_SESSION['upcNameId']." ', '". $_SESSION['statDateFrom'] ." 00:00:00','". $_SESSION['statDateTo'] ." 00:00:00');"))
die($mysqli->error);
//EXEC SQL2
$result = $mysqli->query($sql2)
or die($mysqli->error);
$i=0;
$events = array();
while ($row = $result->fetch_assoc()) {
$events[] = $row;
}
$buildingevents = json_encode($events);
//echo json_encode($events);
$html .= "<script src='/wp-content/plugins/biobelt/moment.min.js'></script>
<script src='/wp-content/plugins/biobelt/fullcalendar.min.js'></script>
<link rel= 'stylesheet' href='/wp-content/plugins/biobelt/fullcalendar.css' type='text/css'>
<script src='/wp-content/plugins/biobelt/fr.js'></script>
<script>
jQuery(document).ready(function() {
var bevents = ".$buildingevents."
console.log(bevents)
jQuery('#calendar').fullCalendar(
{
header: {
right: 'today, month, agendaDay, agendaWeek, prev, next'
},
defaultDate: '" . $_SESSION['statDateFrom'] ."',
events: bevents,
timezone: 'local',
});
});
</script>";
Your events do not match the expected fields of an Event object: see documentation here
Replace the aliases in your query:
titre by title
and
stop by end
and it should be good.

Trying to delete an entry in a table. Query doesn't delete the row, no idea how to debug

I'm trying to delete an entry in my database using the code below. The javascript function takes me to index.php?delpost= with the correct "adventureID" but when I check my database the row is still there. I've very recently started using PDO so I'm wondering if the execute() statement might be the issue. $dbh connect to my database at the top of the page and it is working as it prints every row from the table I'm trying to delete rows from. My goal is to successfully delete a row when I call the javascript function. The issue is - it doesn't.
<script language="JavaScript" type="text/javascript">
function delpost(adventureID, title)
{
if (confirm("Are you sure you want to delete '" + title + "'" + " '" + adventureID + "'"))
{
window.location.href = 'index.php?delpost=' + adventureID;
}
}
</script>
<?php
if(isset($_GET['delpost'])){
$stmt = $dbh->prepare("DELETE FROM adventure WHERE adventureID = :adventureID");
$stmt->execute(array(':adventureID' => $_GET['delpost']));
header('Location: index.php?action=deleted');
exit;
}
?>
<?php
if(isset($_GET['action'])){
echo '<h3>Post '.$_GET['action'].'.</h3>';
}
try {
foreach($dbh->query("SELECT adventureID, title, postDate FROM adventure ORDER BY adventureID DESC") as $row) {
echo '<tr>';
echo '<td>'.$row['title'].'</td>';
echo '<td>'.date('jS M Y', strtotime($row['postDate'])).'</td>';
?>
<td>
Delete
</td>
<?php
echo '</tr>';
}
} catch(PDOException $e) {
echo $e->getMessage();
}
?>
Probably you are facing problem with MYSQL SAFE UPDATES being ON. To avoid it and be able to finally delete rows, you can engage in the following tactics:
SET SQL_SAFE_UPDATES = 0;
--- YOUR DELETE STATEMENT ---
SET SQL_SAFE_UPDATES = 1;
To check if you have SQL_SAFE_UPDATES enabled you can do by running:
SHOW VARIABLES LIKE 'sql_safe_updates'
Try to replace this code :
$stmt = $dbh->prepare("DELETE FROM adventure WHERE adventureID = :adventureID");
$stmt->execute(array(':adventureID' => $_GET['delpost']));
By the following :
$stmt = $dbh->prepare("DELETE FROM adventure WHERE adventureID = :adventureID");
$stmt->bindParam('adventureID', $_GET['delpost']);
$stmt->execute();
Explanation :
You can either : Use ":variable" in your query, then pass variables by binding them with the "bindParam" function.
Or : Use "?" in your query, and then pass variables in the "execute" function.
Full example can be found here : http://php.net/manual/fr/pdostatement.execute.php#example-1050

Send Javascript info to php and save it on a database

A former co-worker developed an a quiz which sended results to a databse. He was fired but i need to use that code again . I only have the javascript code and i need to recreate the php ( save.php) which saves the info from javascript . Can you help me with the php code or give me a hint . Thaks !
$(document).ready(function() {
$("#answer_a").click(function() {
$.get("http://nameOfWebsite/save.php", {test: "1", question: "1", answer: "a" } );
});
$("#answer_b").click(function() {
$.get("http://nameOfWebsite/save.php", {test: "1", question: "1", answer: "b" } );
});
$("#answer_c").click(function() {
$.get("http://nameOfWebsite/save.php", {test: "1", question: "1", answer: "c" } );
});
$("#answer_d").click(function() {
$.get("http://nameOfWebsite/save.php", {test: "1", question: "1", answer: "d" } );
});
});
In save.php use $_GET[] to to use the variables and save them on your table
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$test = mysqli_real_escape_string($con, $_GET['test']);
$question = mysqli_real_escape_string($con, $_GET['question']);
$answer = mysqli_real_escape_string($con, $_GET['answer']);
$sql="INSERT INTO Persons (test, question, answer)
VALUES ('$test', '$question', '$answer')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
Use $_GET[<name>] to get the values in your php and mysqli_connectto insert the data into the table.
You are already on the right track, the next move is in the PHP. You can use this example to get those values. Consider this example:
<?php
if(isset($_GET['test'])) {
$data = array(); // initialize return data holder
$test = isset($_GET['test']) ? $_GET['test'] : null;
$question = isset($_GET['question']) ? $_GET['question'] : null;
$answer = isset($_GET['answer']) ? $_GET['answer'] : null;
// they should be inside now, now you can go on with mysql inserts
// just a sample callback value to check if indeed php got it
$data['test'] = $test;
$data['question'] = $question;
$data['answer'] = $test;
echo json_encode($data);
exit;
}
?>
<!-- lets say this is an image -->
<button id="answer_a" type="button">Hi im an image</button>
<script src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#answer_a").click(function() {
$.get("index.php", {test: "1", question: "1", answer: "a" }, function(response){
var data = $.parseJSON(response);
console.log(data); // check this in console
});
});
});
</script>

How can I pass multiple data from PHP to jQuery/AJAX?

I have a main select list of courses which drives various things on a page. When a course is selected another select list will be repopulated with the start date of that course up to 6 months in advance. Also, I have a table on the page with the students name and phone number, when a course is selected, the table will be repopulated with all the students enrolled onto that course. My problem is I will be getting various different things from PHP via JSON i.e. the students and the starting date. How can I therefore pass more than one thing to jQuery? What if the course select list affected not just 2 things but 3, 5 or even 10? How would we handle that with PHP and jQuery?
foreach($m as $meta)
{
$metaCourse = $this->getCourseInfo($meta['parent_course']);
//populate the select list with the name of each course
$metaSelectList .= '<option id="select'.$count.'" value="'.$metaCourse['id'].'">'.$metaCourse['fullname'].'</option>';
$count++;
//get only the first course's dates
if($count3 == 1)
{
$startDate = intval( $course->getStartDate(50) );
$endDate = strtotime('+6 month', $startDate);
//populates the select list with the starting date of the course up to the next six months
for($date = $startDate; $date <= $endDate ; $date = strtotime('+1 day', $date))
{
$dateSelectList .= '<option id="select'.$count2.'" value="'.$date.'">'.date('D d F Y', $date).'</option>';
$count2++;
}
$count3++;
$students = $s->getStudents($metaCourse['id']);
$content = $this->createStudentTable($students);
}
}
This is my handler for the AJAX...FOR NOW (I haven't implemented the students table yet as I'm still trying to figure out how to pass multiple pieces of data to jQuery). Basically each time a course is selected, PHP creates a new select list with the appropriate dates and then passes it to jQuery. I'm not sure if I should do this in JavaScript or in PHP.
if (isset($_GET['pid']) && (isset($_GET['ajax']) && $_GET['ajax'] == "true"))//this is for lesson select list
{
$pid = intval( $_GET['pid'] );
$c = new CourseCreator();
$startDate = intval( $c->getStartDate($pid) );
$endDate = strtotime('+6 month', $startDate);
$dateSelectList = '<select name="dateSelect" id="dateSelect">';
//populates the select list with the starting date of the course up to the next six months
for($date = $startDate; $date <= $endDate ; $date = strtotime('+1 day', $date))
{
$dateSelectList .= '<option id="select'.$count2.'" value="'.$date.'">'.date('D d F Y', $date).'</option>';
$count2++;
}
$dateSelectList .= '</select>';
echo json_encode($dateSelectList);
exit;
}
My jQuery handler:
$('#metaSelect').live('change', function()
{
$.getJSON('?ajax=true&pid='+$('#metaSelect').val(), function(data)
{
alert(data);
$('#dateSelectDiv').html(data);
});
});
You can easily pass ALOT of data from PHP to your HTML via JSON (which you seem to of put in basic already)
However to expand on what you have - heres a quick example
<?php
$arrayOfStuff = array("theKey" => "theEntry", 123 => "Bob Dow", 56 => "Charlie Bronw", 20 => 'Monkey!', "theMyID" => $_POST['myID']);
echo json_encode($arrayOfStuff);
?>
On your HTML side.
<script>
$.post("/theurl/", {type: "fetchArrayOfStuff", myID: 24}, function(success) {
//your success object will look like this
/*
{
theKey: 'theEntry',
123: 'Bob Dow',
56: 'Charlie Bronw',
20: 'Monkey!',
theMyID: 24
}
so you can easily access any of the data.
alert(success.theKey);
alert(success[123]);
alert(success[56]);
alert(success[20]);
alert(success.theMyID);
*/
//we can iterate through the success JSON!
for(var x in success) {
alert(x + "::" + success[x]);
};
}, "json");
</script>
In the long run - your MUCH better of letting the backend do the backend stuff, and the front end doing the front-end stuff.
What this means is, try keep the HTML generation as far away as possible from the back-end, so instead of constantly passing
for($date = $startDate; $date <= $endDate ; $date = strtotime('+1 day', $date))
{
$dateSelectList .= '<option id="select'.$count2.'" value="'.$date.'">'.date('D d F Y', $date).'</option>';
$count2++;
}
You could perhaps
$date = $startDate;
$myJson = array()
while($date <= $endDate) {
$myJson[] = array("date" => $date, "formattedDate" => date('D d F Y', $date));
$date += 86400; //86400 is the value of 1 day.
}
echo json_encode($myJson);
And you can just do a simple iteration on your HTML code.
<script>
$.get("/", {ajax: true, pid: $('#metaSelect').val()}, function(success) {
//we can iterate through the success JSON!
var _dom = $('#dateSelectDiv').html(''); //just to clear it out.
for(var x in success) {
_dom.append("<option value='"+success[x].date+"'>"+success[x].formattedDate+"</option>");
};
}, "json");
</script>
So as you can see - you can pass alot of data using JSON
Maybe look at some of the documentation to - http://api.jquery.com/jQuery.get/ , http://api.jquery.com/jQuery.post/ - might give you more ideas.
Best of luck to you

Categories

Resources