Fullcalendar isn't loading my json to show events - javascript

I've been messing around with the fullcalendar java script and I can't seem to get the calendar to load any of the data my mysql database.
My db-connect.php file returns the first entry in the table when I test it, but still isn't populated onto the calendar.
<?php
// List of events
$events = array();
// connection to the database
$mysqli = new mysqli("localhost","username","password","database");
//check connection
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
//fetches and sends data in string
$result = $mysqli->query("SELECT * FROM events ORDER BY id");
$events = $result->fetch_array(MYSQLI_ASSOC);
echo json_encode($events);
?>
I also have a get_events.php that I tried setting up to only pull the date range. It doesn't pull any info when I test it but that should be because I'm testing it without a date range.
<?php
// List of events
$events = array();
$start = $_GET["start"];
$end = $_GET["end"];
// connection to the database
$mysqli = new mysqli("localhost","agaraapp_events","!QAZ#WSX3edc4rfv","agaraapp_events");
//check connection
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
//fetches and sends data in string
$query = mysqli_query($link, "SELECT * FROM events WHERE start >= '$start' AND end <= '$end'");
while($fetch = mysqli_fetch_array($query,MYSQLI_ASSOC)) {
$e = array();
$e['id'] = $fetch['id'];
$e['title'] = $fetch['title'];
$e['start'] = $fetch['start'];
$e['end'] = $fetch['end'];
array_push($events, $e);
}
echo json_encode($events);
?>
Then here is my calendar code.
<head>
<meta charset="utf-8" />
<link href="CalendarJava/main.css" rel="stylesheet" />
<script src="CalendarJava/main.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
schedulerLicenseKey: 'CC-Attribution-NonCommercial-NoDerivatives',
initialView: 'dayGridMonth',
events: {
url: 'get_events.php',
type: 'POST',
data : {
},
success : function(response){
}
}
});
calendar.render();
});
</script>
</head>
I've changed the url to both get_events.php and db-connect.php but everytime I load it up it shows a blank calendar. I'm guessing I need an Ajax code but I'm not very schooled up on those. If that's what I'm missing then I'll try and study up on it and add it in.
Any help with what is going wrong would be helpful. I've read a bunch of of "related" issues on this but none of those problems seem to be correcting my problem.
EDIT1
db-connect.php returns the following results, which appears to be the correct format
{"id":"1","title":"Test","start":"2021-02-06 10:38:24","end":"2021-02-06 12:38:24"}
There are no errors on the server side either

You can try the following, which first returns the JSON response as array and second the correct response header is set.
<?php
// List of events
$events = array();
// connection to the database
$mysqli = new mysqli("localhost","username","password","database");
//check connection
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit;
}
//fetches and sends data in string
$result = $mysqli->query("SELECT * FROM events ORDER BY id");
while ($event = $result->fetch_array(MYSQLI_ASSOC)) {
$events[] = $event;
};
// response should be associated with the correct header setting
header('Content-Type: application/json; charset=utf-8');
// now we can JSON the response
echo json_encode($events);
// in case we have some more code afterwards in some if statements
exit;
?>

Related

Access Json Array from HTTP Get request and Update Page every 1s Using AJAX or JQUERY

So, I'm working on a project which involves getting data from my website into the ESP32. I came across making the Json array and updating the info from time to time, but now I need to get the specific info from my Json array so I can use it with my ESP. For some reason when I try to access the data from my page, I'm getting 0 instead of the number that is in that place, in the case of text, I don't receive anything as a response. I fixed not receiving any response from the file, I had to create a separate PHP file in which get the database info and turns that info in a datajson.json file, so the code that I have works, but I will need to update the PHP file every 1 second, I saw that Ajax was the way to go since I wouldn't need to refresh the page every time, only the content
ESP32 code:
void loop() {
if ((WiFi.status() == WL_CONNECTED)) { //Check the current connection status
HTTPClient http;
http.begin("https://nps-tech.com.br/receive.php"); //Specify the URL and certificate
int httpCode = http.GET();
if (httpCode > 0)//Check for the returning code
{
String payload = http.getString();
Serial.println("\nStatuscode: "+ String(httpCode));
Serial.println(payload);
char json[500];
payload.replace(" ", "");
payload.replace("\n", "");
payload.trim();
payload.remove(0,1);
payload.toCharArray(json, 500);
StaticJsonDocument<200> doc;
deserializeJson(doc, json);
int id = doc["AutoIncrement"];
const char* nome = doc["Nome Aparelho"];
int stat = doc["Status"];
Serial.println(id);
Serial.println(nome);
Serial.println(stat);
}
else
{
Serial.println("Error on HTTP request");
}
http.end(); //Free the resources
}
delay(10000);
}
New response from ESP32:
Statuscode: 200
[{"AutoIncrement":"1","Aparelho":"LED","Status":"0"}]
1
LED
0
PHP Code, How can I set a SetInterval to update get_data function from php every 1 second, without reloading the page:
<!DOCTYPE html>
<html lang="pt-br">
<head>
</head>
<body>
<?php
function get_data()
{
$servername = "stuuf";
$dBUsername = "stuuf";
$dBPassword = "stuuf";
$dBname = "stuuf";
$conn = mysqli_connect($servername, $dBUsername, $dBPassword, $dBname);
if ($conn->connect_error){
die ("Connection failed". $conn->connect_error);
}
$sql = "SELECT * FROM dados;";
$result = mysqli_query($conn, $sql);
$json_array = array();
while($row = mysqli_fetch_assoc($result))
{
$json_array[] = array(
'AutoIncrement' => $row["AutoIncrement"],
'Aparelho' => $row["aparelho"],
'Status' => $row["Status"],
);
}
return json_encode($json_array);
}
$file_name = 'dadosjson' . '.json';
if (file_put_contents($file_name, get_data()))
{
echo $file_name. ' file created';
}
else
{
echo 'There is some error';
}
?>
<script>
setInterval(1000);
//ajax to update every 1s
</script>

PHP code not returning correct MySQL result

I'm querying a set of data from MySQL on a hosted server. When I did it on my local machine, it worked fine, but on the hosted server, it's not returning anything. The weird thing is, when I use this GUI for the hosted environment to run the same query, it does return the results.
So here are some codes, etc.
This is index.php:
<?php
$servername = "username.db.theservername.ether.com";
$mysqllogin = "username";
$mysqlpassword = "thepassword";
$dbName = "StepsMath";
$conn = new mysqli($servername, $mysqllogin, $mysqlpassword, $dbName);
if($conn->connect_error){
die ("connection failed: " . $conn->connect_error);
echo "connection failed.";
}
$set_name = 'test_set';
$query = "select word, definition from word_list where set_name = '$set_name'";
$result = $conn->query($query);
$conn->close();
// *********************************************
echo $query; // <-------- *******this prints the query*******
// *********************************************
$result = mysqli_fetch_array($result);
?>
<!DOCTYPE html>
<html lang="en"><head>
<title>this is a title</title>
<script type="text/javascript">
var json = '<?= json_encode($result) ?>';
var word_list = JSON.parse(json);
console.log(word_list); //line 24
console.log(json); //line 25
function getUserId(){
return '<?= $user_id ?>';
}
if(!getUserId()) window.location = 'login.html';
</script>
</head>
<body>body stuff</body>
</html>
Table word_list only has three columns: word, definition, and set_name
The above code is supposed to return rows of words and definitions. Instead, as I check in the browser console, it returns the following:
{"current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null}
This is the query that runs:
select word, definition from word_list where set_name = 'test_set'
If I copy that exact query and run it in the MySQL GUI in the hosted server,
the following is returned:
So to summarize the question, why is there a discrepancy in the result between the GUI and the code??
change this line:
$result = mysqli_fetch_array($result);
to this:
while ($row = mysqli_fetch_assoc($result)) {
$res[] = $row;
}
var_dump($res);
The information you previously got: {"current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null} are all mysqli_result properties.
Read this, it will help you uderstand what you did wrong:http://php.net/manual/en/class.mysqli-result.php

Access DB from html file via custom PHP file

Right now I have working a DB connection to mysql. The html -> PHP -> query -> data reception works. I show the relevant code:
From the html file matters:
d3.json("http://path/file.php", function(error, data) {
console.log (data);
});
file.php:
<?php
$username = "myusername";
$password = "mypassword";
$host = "myhost";
$database="myDB";
$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);
$myquery = "select * from `mytable`";
$query = mysql_query($myquery);
if ( ! $query ) {
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
echo json_encode($data);
mysql_close($server);
?>
What I want is to have only 1 .php file instead of 1 php file for every query. That means I need to send from the html a variable inputquery to the php file. I've tried several things such as changing:
`$myquery = "select * from `mytable`; into `$myquery = inputquery`;
And I think that the wrong point is the definition of the function that requests the data from the DB. What I tried (wrong, the following code does not work as expected):
var inputquery = "select * from `mytable`"
d3.json("http://serverhost/path/file.php", function(error, data) {
console.log (data);
});
Maybe this is not working because I am not telling the function I want as an input to the .php file the variable inputquery. I tried to put it inside the function, but got "data is not defined" errors, so I think it is not worth it to show the wrong code.
How can I input that var inputquery to the .php file? It could not be the way I planned it.
Thank you
You have to send the inputquery variable with the http request as POST data,
then in you php file you can do :
$myquery = $_POST['inputquery'];
You surely will find some documentation about sending post data with the request you're sending.
The simplest way is using get parameter in d3.json:
var yourparam = 'mytable';
d3.json("http://path/file.php?query=" + yourparam, function (error, json) {
...
});
You can retrieve the variable from the $_GET array.
Finally don't put mysql commmands into your js, and don't use mysql library. It's very dangerous.
This is a very bad idea, since you become very vulnerable to SQL Injection, even so I will try to help you
I assume you have JQuery if you have so
you can do the following
html.file
var inputquery = "select * from `mytable`";
$.post("relative/path/to/file.php",
{query : inputquery},
function (data) {
alert(data); // See output
},'json);
file.php
<?php
$username = "myusername";
$password = "mypassword";
$host = "myhost";
$database="myDB";
$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);
$myquery = $_POST['query'];
$query = mysql_query($myquery);
if ( ! $query ) {
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
echo json_encode($data);
mysql_close($server);
?>

Accessing MySQL database in d3.js with php file

I need some help with MySQL and D3 with a php file.
I am trying to get access to my database using D3. I have created a php file where I make the connection to MySQL.
My problem is however that I get an empty array when printing out my output to the console from D3. I can't seem to find what I am doing wrong. Below is my code for both the D3 call and the php file: (I have appropriate names from username, password and database name.)
<?php
$host = "localhost";
$port = 8889;
$username = "********";
$password = "********";
$database="***datebasename***";
if (!$server) {
die('Not connected : ' .mysql_error());
}
$server = mysql_connect($host, $user, $password);
$connection = mysql_select_db($database, $server);
if (isset($_GET['type'])) {
$type = $_GET['type'];
} else {
$type = "null";
echo "Type not passed";
}
if($type=='load'){
$string = '';
$gene = $_GET["gene"];
$data = $_GET["data"];
$myquery = "select gene_data.gene_data from genes inner join gene_data on genes.id=gene_data.g_id where genes.name ='$gene' and genes.type='$data'";
$query = mysql_query($myquery);
if ( !$myquery || !$query) {
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
echo json_encode($data);
mysql_close($server);
}
?>
My file are all running from a server. The MySQL server is also on the same server, so I jut call localhost to get access. Also since I need several different parameters for my SQL calls I send the values from D3 ("gene" and "human").
The following the call I make from D3:
d3.json("getdata.php?type=load&gene=CLL5&data=human", function(error, data) {
console.log(data);
});
Also it is worth mentioning that my query is tested and works.
Some help would be greatly appreciated! Any ideas on how to debug with and prints or write.outs would be appretiated as well!

Does SJCL content need to be json_encode(d) when it is read from a database?

Overview
I am attempting to encrypt data, send it to a database, then decrypt the data using the Stanford Javascript Crypto Library (SJCL).
Problem
Whenever I attempt to call the data from the database, I get a "CORRUPT: ccm: tag doesn't match" error. I have looked this up and it seems as if my content or password is corrupted, and because the password is being straight from a textbox, I have narrowed it down to the content.
Code Snippet
(PHP)
$paste = $_GET['url'];
$query = "SELECT * FROM posts WHERE url='$paste'";
$result = mysqli_query($db, $query);
$row = mysqli_fetch_array($result);
$t = $row['title'];
$c = $row['content'];
$con = json_encode($c);
$e = $row['encode'];
$ca = $row['Catagory'];
$en = $row['encrypted'];
(Javascript) -Invokes SJCL-
<script type="text/javascript">
var content = <?php echo $con; ?>;
function decryptPaste() {
try {
sjcl.decrypt(document.getElementById("decrypt-pass").value, content)
} catch (e) {
alert("Can't decrypt: " + e);
}}
Any and all help appreciated, thanks in advance!

Categories