I am trying to populate a chart using JSON data which has been retrieved from a Database using PHP. I have done some research before coming to stackoverflow. I am using anychart's bar chart formatting. Below is my PHP code:
if (isset($_POST['myData'])){
$integer = $_POST['myData'];
if ($integer === "3"){
include 'db_connection.php';
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$return_arr3 = array();
$query = "SELECT Wins, Loses, Draws FROM `record` WHERE Year = '2019/2020'";
$result = mysqli_query($conn,$query);
while($row = mysqli_fetch_array($result)){
$wins = $row['Wins'];
$loses = $row['Loses'];
$draws = $row['Draws'];
$return_arr3[] = array("Wins" => $wins,
"Loses" => $loses,
"Draws" => $draws);
echo($return_arr3);
}
// Encoding array in JSON format
echo json_encode($return_arr3);
}
Then here is my HTML code.
<div id="minutes_popup" class="popupcontainer">
<script src="https://cdn.anychart.com/releases/8.8.0/js/anychart-base.min.js"></script>
<script src="https://cdn.anychart.com/releases/8.8.0/js/anychart-data-adapter.min.js"></script>
</div>
Finally, here is my JavaScript code.
$("#minutes").click(function(){
alert("Button works");
$("#minutes_popup").toggle();
var integer = $("#minutes").attr("name");
alert("integer: " + integer);
$.ajax('includes/test.php', {
type: 'POST', // http method
data: {myData: integer},// data to submit
dataType: 'json',
success: function(response){
anychart.onDocumentReady(function () {
anychart.data.loadJsonFile("includes/test.php", function (response) {
// create a chart and set loaded data
chart = anychart.bar(response);
chart.container("minutes_popup");
chart.draw();
});
});
}
});
});
This code doesn't work for some reason unknown to me. No errors appear on the console and the data is echoed to the console in this format:
[{"Wins":"34","Loses":"19","Draws":"10"}]
However, a bar chart is not being created.
If anyone could tell me how to fix my code, I would be very grateful.
Related
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;
?>
I'm aiming to display dots with javascript by their coordinates. Each person click on an image, (X,Y) will be stored in the database. On the same image will be displayed all dots, when a person is visualing the image with dots and another person will submit new dot, this last will appears because array_x and array_y tabs will be refreshed every 1s.
The question is : is it the best way in terms of using server ressources of doing that ? suppose i've 1000 persons that will participate to this study, that signify that for one person there is at least one request every 1s. Suppose that one person will spend 30s, that will be a huge amount of requests.
I am afraid to have a server breakdown due to multiple requests. Is it a way more guaranteed than this one ?
My js :
window.setInterval(loadNewPosts, 1000); //load simultaneous choice in 1 second
function loadNewPosts(){
$.ajax({
type: "GET",
cache: false,
dataType: "json",
url: "latest.php",
data: "current_id=" + current_id +"&nextType=" + nextType,
success: function(data) {
for (var i = 0; i < data['array_x'].length; i++) {
array_x.push(data['array_x'][i]);
array_y.push(data['array_y'][i]);
}
}
});
}
my php latest.php :
$servername = "";
$username = "";
$password = "";
$dbname = "";
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$current_id = intval($_GET['current_id']);
$Type = (string)$_GET['nextType'];
$sql = "SELECT * FROM `table` WHERE id > $current_id and Type='".$Type."'";
$result = mysqli_query($conn, $sql);
$array_x= [];
$array_y= [];
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
array_push($array_x,$row["X"]);
array_push($array_y,$row["Y"]);
}
} else {
echo "";
}
mysqli_close($conn);
// return the posts as a JSON object
header('Content-Type: application/json');
$data=array(
'array_x' => $array_x,
'array_y' => $array_y
);
echo json_encode($data);
I am trying to connect MySQL database using PHP as a REST API and Knockout JS to display the database in the UI. I am able to make a connection from database to PHP and query the data. As am new to knockout, I am not sure on how to display the data properly using Knockout. Please find my code below. Thanks for your help in advance.
PHP Code:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "employeedb";
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT `id`, `firstname`, `lastname`, `currentAddress`, `permanentAddress` FROM `employeedata` WHERE 1";
$result = $conn->query($sql);
$records = array();
while($row = $result->fetch_array()) {
$records[] = array(
'id' => $row['id'], 'firstname' => $row['firstname'], 'lastname' => $row['lastname'], 'currentAddress' => $row['currentAddress'], 'permanentAddress' => $row['permanentAddress']
);
}
echo json_encode($records);
?>
JS Code:
var dataModel = function () {
var self = this;
this.employeeRecord = ko.observableArray([]);
// Display Records
this.displayRecord = function () {
$.ajax({
type : 'GET',
datatype: "json",
url: "js/phpapi.php",
success: function (data) {
var id = data['id'];
var firstname = data['firstname'];
var lastname = data['lastname'];
var currentAddress = data['currentAddress'];
var permanentAddress = data['permanentAddress'];
self.employeeRecord.push(data);
}
});
};
this.displayRecord();
console.log (self.employeeRecord());
};
ko.applyBindings(new dataModel());
I am able to 'GET' the 'URL' correct but the entire data is displayed in array [0]. Let me know if I am missing something.
Output: when console.log (data)
"[{"id":"1","firstname":"Test Data","lastname":"number 1","currentAddress":"Temporary Current Address 1","permanentAddress":"Permanent Address 1"},
{"id":"2","firstname":"Test Data","lastname":"number 2","currentAddress":"Temporary Current Address 2","permanentAddress":"Permanent Address 2"}]"
This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 7 years ago.
I am not very experienced in web programming and am attempting to run a script which updates my database.
<script>
function myFunction() {
var texts = document.getElementById("content").textContent;
alert(texts)
<?php
include_once 'accounts/config.php';
$text = ...;
$tbl_name='enemies'; // Table name
$query = "UPDATE enemies SET text=('$text') WHERE id=1";
$result = mysql_query($query) or die(mysql_error());
?>
}
</script>
I have no idea what to put in the $text section as shown with $text = ...; in order to get the variable texts from above.
EDIT
I have updated my code but the function does not seem to be accessing the PHP file. I am using a button to call the function and I have also tested it so i know the function is being called. My file is called update.php and is in the same directory as this file.
<button onclick="myFunction()">Click This</button>
<script>
function myFunction() {
var texts = document.getElementById("content").textContent;
$.ajax({
url: "update.php",
type: "POST",
data: {texts:texts},
success: function(response){
}
});
}
</script>
you can post your $texts value to other php page using ajax and get the variable on php page using $_POST['texts'] and place update query there and enjoy....
function myFunction() {
var texts = document.getElementById("content").textContent;
$.ajax({
url: 'update.php',
type: "POST",
data: {texts:texts},
success: function(response)
{
}
});
And your php file will be named as update.php
<?php
include_once 'accounts/config.php';
$text =$_POST['texts'];
$tbl_name='enemies'; // Table name
$query = "UPDATE `enemies` SET `text`='".$text."' WHERE `id`=1";
$result = mysql_query($query) or die(mysql_error());
?>
PHP runs on the server and then generates output which is then returned to the client side. You can't have a JavaScript function make a call to inlined PHP since the PHP runs before the JavaScript is ever delivered to the client side.
Instead, what you'd need to do is have your function make an AJAX request to a server-side PHP script that then extracts the data from the request body and then stores it in the database.
PHP: "/yourPhpScript.php"
<?php
include_once 'accounts/config.php';
$text = $_POST['data'];
$tbl_name='enemies'; // Table name
$query = "UPDATE enemies SET text='".$text.'" WHERE id=1";
$result = mysql_query($query) or die(mysql_error());
?>
JavaScript:
function myFunction() {
var texts = document.getElementById("content").textContent;
alert(texts);
// append data as a query string
var params = 'data='+texts;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
// when server responds, output any response, if applicable
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
// replace with the filename of your PHP script that will do the update.
var url = '/yourPhpScript.php';
xmlhttp.open("POST", url, true);
xmlhttp.send(params);
}
A word of caution: This is not a safe, production-friendly way of updating data in your database. This code is open to SQL injection attacks, which is outside the scope of your question. Please see Bobby Tables: A guide to preventing SQL injection if you are writing code that will go into production.
You are wrong in approach
You should use ajax to post 'texts' value to your php script
https://api.jquery.com/jquery.post/ and create separate php file where you will get data from ajax post and update DB
javascript:
<script>
function myFunction() {
var texts = document.getElementById("content").textContent;
$.ajax({
type: "POST",
url: "update.php",
data: "texsts=" + texts,
success: success
});
}
</script>
update.php
<?php
include_once 'accounts/config.php';
$text = $_POST['texts'];
$tbl_name='enemies'; // Table name
$query = "UPDATE enemies SET text=('$text') WHERE id=1";
$result = mysql_query($query) or die(mysql_error());
?>
i will use PDO if i was you, what you do mysql_query are outdated, if you use my framework https://github.com/parisnakitakejser/PinkCowFramework you can do the following code.
<?php
include('config.php');
$text = $_POST['text'];
$query = PinkCow\Database::prepare("UPDATE enemies SET text = :text WHERE id = 1");
$bindparam = array(
array('text', $text, 'str')
);
PinkCow\Database::exec($query,$bindparam);
$jsonArray = array(
'status' => 200
);
echo json_encode($jsonArray);
?>
place this code in jsonUpdateEnemies.php file and call it width jQuery
<script>
function myFunction(yourText) {
$.post( 'jsonUpdateEnemies.php', {
'text' : yourText
}, function(data)
{
alert('Data updated');
},'json');
}
</script>
its a little more complex then you ask about, but its how i will resolved your problem, :)
so I currently have this PHP script to get the Youtube IDS set in a mySQL database. This PHP script lists all the Youtube ID's in the database.
PHP
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "songrequests";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM test";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "song: " . $row["link"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Ok, and after that, I found this script that pushes Youtube IDs to a playlist, this is found here on jsFiddle (Full demo here)
So basically, what I am trying to achieve is to push the IDs from my database to the list. I created a json which lists all of the IDs here
With this ajax I'm trying to push the ID's from the json to the list, but it does not seem to work.
JS
$.ajax({
url: 'http://dj.aotikbot.tv/songlist.php',
type: 'GET',
dataType: 'json',
success: function(data) {
console.log(data.songs.length);
if (data.songs.length != 0) {
for (var x = 0; x < data.songs.length; x++) {
ytplayer_playlist.push("'" + data.songs[x].link + "'");
}
}
},
error: function() { console.log('Uh Oh!'); },
});
If you need more info on what I'm trying to do, let me know. Thanks in advance.
So, based on our chat, JSONP is what you went after. The code below should work. Take a look.
var playlist = [];
$.ajax({
url: 'http://dj.aotikbot.tv/songlist.php?callback=?',
type: 'GET',
async: false, //evil, but you needed this!
dataType: 'json',
success: function(data) {
if (data.songs.length > 0) {
$.each(data.songs, function() {
playlist.push(this.link);
});
}
console.log("Here is your playlist");
console.log(playlist);
},
error: function() { console.log('Uh Oh!'); }
});