Rendering complex JSON from mysql and use column value as label - javascript

I have a table with 1000 records and a corresponding data history of 5 years, including events. The table structure looks like this at the moment:
id|date|reference_id|account_id|dataSet|price|title|type|description
1|2006-01-03|ID00001|1|dataSet01|44.23|Analyst opinion change|A|Upgrade by Bank from Sell to Hold
2|2006-01-03|ID00002|1|dataSet02|62.75|||
3|2006-01-03|ID00003|1|dataSet03|25.95|Dividend|D|Amount: 0.22
4|2006-01-03|ID00004|2|dataSet04|31.81|||
5|2006-01-03|ID00005|3|dataSet05|78.20|||
6|2006-02-01|ID00001|1|dataSet01|45.85|Dividend|D|Amount: 0.30
7|2006-02-01|ID00002|1|dataSet02|59.37||
8|2006-02-01|ID00003|1|dataSet03|27.59|Dividend|D|Amount: 0.26
9|2006-02-01|ID00004|2|dataSet04|34.24|||
10|2006-02-01|ID00005|3|dataSet05|83.42|||
11|2006-03-01|ID00001|1|dataSet01|45.54|Analyst opinion change|A|Upgrade by Bank from Sell to Hold
12|2006-03-01|ID00002|1|dataSet02|60.86|||
13|2006-03-01|ID00003|1|dataSet03|27.04|Downgrade by Bank from Buy to Hold
14|2006-03-01|ID00004|2|dataSet04|36.04|||
15|2006-03-01|ID00005|3|dataSet05|84.32|||
I want to render the data depending on account_id (in this case account_id = 1) to get the following JSON:
{
"data": [{
"date": "2006-01-03",
"dataSet01": "44.23",
"dataSet02": "62.75",
"dataSet03": "25.95"
}, {
"date": "2006-02-01",
"dataSet01": "45.85",
"dataSet02": "59.37",
"dataSet03": "27.59"
}, {
"date": "2006-03-01",
"dataSet01": "45.54",
"dataSet02": "60.86",
"dataSet03": "27.04"
}],
"events": [{
"dataSet01": [{
"date": "2006-01-03",
"title": "Analyst opinion change",
"text": "A",
"description": "Upgrade by Bank from Sell to Hold"
}, {
"date": "2006-02-01",
"title": "Dividend",
"text": "D",
"description": "Amount: 0.30"
}, {
"date": "2006-03-01",
"title": "Analyst opinion change",
"text": "A",
"description": "Upgrade by Bank from Sell to Hold"
}]
},{
"dataSet03": [{
"date": "2006-01-03",
"title": "Analyst opinion change",
"text": "A",
"description": "Upgrade by Bank from Sell to Hold"
}, {
"date": "2006-02-01",
"title": "Dividend",
"text": "D",
"description": "Amount: 0.30"
}, {
"date": "2006-03-01",
"title": "Analyst opinion change",
"text": "A",
"description": "Downgrade by Bank from Buy to Hold"
}]
}]
}
I'm struggling to build the json though. As of right now I'm rendering the data like this:
$query = "SELECT date, price
FROM datatable
WHERE account_id = 1
ORDER BY date ASC";
$result = mysql_query( $query );
$data = array();
while ( $row = mysql_fetch_assoc( $result ) ) {
$data[] = $row;
}
return json_encode( $data );
Obviously this returns the json with price as label for each record value (price). How should the query look like instead to render the above json example?

$query = "SELECT *
FROM datatable
WHERE account_id = 1
ORDER BY date ASC";
$result = mysql_query( $query );
// Define temporary arrays
$data = array();
$events = array();
while ( $row = mysql_fetch_assoc( $result ) ) {
// Assemble the data grouped by date and dataset
if ( !isset($data[$row['date']]) )
{
$data[$row['date']] = array(
'date' => $row['date'],
);
}
// Inject dataSet in $data grouped by date
if ( !isset($data[$row['date']][$row['dataSet']]) )
{
$data[$row['date']][$row['dataSet']] = $row['price'];
}
// Assemble events grouped by dataSet
if ( !isset($events[$row['dataSet']]) )
{
$events[$row['dataSet']] = array();
}
$events[$row['dataSet']][] = array(
'date' => $row['date'],
'title' => $row['title'],
'text' => $row['type'],
'description' => $row['description']
);
}
// Remove date keys
$data = array_values($data);
return json_encode(array(
'data' => $data,
'events' => $events
));

Related

How do include/call this Javascript file in PHP?

I am writing a PHP script that uses Twitters API's to get a response of tweets in JSON. I am then using the id's in this JSON as parameters in Twitter's widgets.createTweet() function.
The official twitter documentation for this can be found here.
I believe the problem is at the point where I am trying to icnlude the Twitter widgets.js file within my PHP script.
Here is my entire PHP script with my keys and tokens redacted:
<?php
echo "<h2>Simple Twitter API Test</h2>";
require_once('TwitterAPIExchange.php');
$settings = array(
'oauth_access_token' => ""
'oauth_access_token_secret' => ""
'consumer_key' => ""
'consumer_secret' => ""
)
$url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
$requestMethod = "GET";
if (isset($_GET['user'])) {$user = preg_replace("/[^A-Za-z0-9_]/", '', $_GET['user']);} else {$user = "iagdotme";}
$getfield = "?screen_name=$user&count=$count";
$twitter = new TwitterAPIExchange($settings);
$string = json_decode($twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest(),$assoc = TRUE);
if(array_key_exists("errors", $string)) {echo "<h3>Sorry, there was a problem.</h3><p>Twitter returned the following error message:</p><p><em>".$string[errors][0]["message"]."</em></p>";exit();}
$number_tweets = count($string['statuses']);
// THIS IS THE PROBLEM AREA ///////////
echo "<script sync src='https://platform.twitter.com/widgets.js'></script>"
echo "<div class='cols'>";
foreach ($tweet_array['statuses'] as $tweet ) {
$id = $tweet["id"];
echo "<div class='grid-item'><div id='container-$id'></div></div>";
$js_array[] = "twttr.widgets.createTweet('$id', document.getElementById('container-$id'));";
}
echo "</div>";
echo '<script>';
$t = 1;
foreach ($js_array as $js) {
echo $js;
$t++;
}
echo '</script>';
?>
I believe the problem is where I am trying to include the js file from https://platform.twitter.com/widgets.js
It seems to me like everything else here should work. This php file doesn't give me any errors when I try to open it in a browser. I am stuck.
What I'm tyring to do with this code:
make an API call to Twitter and retrieve a set of tweets
use the id's in those tweets to pass
How am I trying to do it:
Using php I have made a successful API call to Twitter with the assistance of an open sourced php library/api wrapper.
store the JSON response in an array, loop through that array getting the tweet id's (attributes for each tweet within the json)
use those id's as parameters for twitter's createTweet function
What my problem is:
I think the problem is, is that my code doesn't know what I mean when I use the twttr.widgets.createTweet() js function because htts://platform.twitter.com/widgets.js is not included properly.
To reiterate, this is where I am trying to include that file:
echo "<script sync src='https://platform.twitter.com/widgets.js'></script>"
Is that piece included properly? If so, are there other things that pop out as erroneous?
Here is a sample of the JSON response from the twitter API call.
{
"statuses": [
{
"created_at": "Wed May 15 15:13:53 +0000 2019",
"id": 1128679903329542144,
"id_str": "1128679903329542144",
"text": "Araw-gabi nasa isip ka, napapanagip ka kahit sa'n magpunta",
"truncated": false,
"entities": {
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": []
},
"metadata": {
"iso_language_code": "tl",
"result_type": "recent"
},
"source": "Twitter for Android",
"in_reply_to_status_id": null,
"in_reply_to_status_id_str": null,
"in_reply_to_user_id": null,
"in_reply_to_user_id_str": null,
"in_reply_to_screen_name": null,
"user": {
"id": 1016132854999183360,
"id_str": "1016132854999183360",
"name": "L Y S Ađź’›",
"screen_name": "ilysachn",
"location": "Homeđź“Ť",
"description": "",
"url": null,
"entities": {
"description": {
"urls": []
}
},
"protected": false,
"followers_count": 97,
"friends_count": 73,
"listed_count": 0,
"created_at": "Mon Jul 09 01:32:06 +0000 2018",
"favourites_count": 624,
"utc_offset": null,
"time_zone": null,
"geo_enabled": true,
"verified": false,
"statuses_count": 188,
"lang": "en",
"contributors_enabled": false,
"is_translator": false,
"is_translation_enabled": false,
"profile_background_color": "F5F8FA",
"profile_background_image_url": null,
"profile_background_image_url_https": null,
"profile_background_tile": false,
"profile_image_url": "http://pbs.twimg.com/profile_images/1125769288797675520/3Ez4FP9n_normal.jpg",
"profile_image_url_https": "https://pbs.twimg.com/profile_images/1125769288797675520/3Ez4FP9n_normal.jpg",
"profile_banner_url": "https://pbs.twimg.com/profile_banners/1016132854999183360/1553425392",
"profile_link_color": "1DA1F2",
"profile_sidebar_border_color": "C0DEED",
"profile_sidebar_fill_color": "DDEEF6",
"profile_text_color": "333333",
"profile_use_background_image": true,
"has_extended_profile": false,
"default_profile": true,
"default_profile_image": false,
"following": false,
"follow_request_sent": false,
"notifications": false,
"translator_type": "none"
},
"geo": null,
"coordinates": null,
"place": null,
"contributors": null,
"is_quote_status": false,
"retweet_count": 0,
"favorite_count": 0,
"favorited": false,
"retweeted": false,
"lang": "tl"
},
If you want to know what syntax errors you have in runtime use phpstorm.
I fix errors and now code looks like this
and your script will connect in php file.
<?php
echo "<h2>Simple Twitter API Test</h2>";
require_once('TwitterAPIExchange.php');
$settings = [
'oauth_access_token' => "",
'oauth_access_token_secret' => "",
'consumer_key' => "",
'consumer_secret' => ""
];
$url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
$requestMethod = "GET";
if (isset($_GET['user'])) {
$user = preg_replace("/[^A-Za-z0-9_]/", '', $_GET['user']);
} else {
$user = "iagdotme";
}
$getfield = "?screen_name=$user&count=$count";
$twitter = new TwitterAPIExchange($settings);
$string = json_decode($twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest(),$assoc = TRUE);
if(array_key_exists("errors", $string)) {
echo "<h3>Sorry, there was a problem.</h3><p>Twitter returned the following error message:</p><p><em>".$string["errors"][0]["message"]."</em></p>";exit();
}
$number_tweets = count($string['statuses']);
?>
<script sync src='https://platform.twitter.com/widgets.js'></script>
<?php
echo "<div class='cols'>";
foreach ($tweet_array['statuses'] as $tweet ) {
$id = $tweet["id"];
echo "<div class='grid-item'><div id='container-$id'></div></div>";
$js_array[] = "twttr.widgets.createTweet('$id', document.getElementById('container-$id'));";
}
echo "</div>";
?>

Using Jest to test Jquery that calls PHP ajax

I have a Javascript file with a function I'm trying to test. All the function does is make a jQuery post request to a PHP ajax file (see code)
function loadTeams(clubID){
var data = {
action: 'loadClubTeams',
clubID: clubID
};
return jQuery.post('/ajax/calendar_ajax.php', data);
}
I have a mock set up in my /__mocks__/ dir as such:
<?php
$teams = array(
array(
"Name" => "Team 1",
"ClubID" => 34
),
array(
"Name" => "Team 2",
"ClubID" => 34
),
array(
"Name" => "Team 3",
"ClubID" => 35
)
);
$response = array();
if($_REQUEST['action'] == "loadClubTeams"){
foreach($teams as $team){
if($team['ClubID'] == $_REQUEST['ClubID']){
array_push($response, $team);
}
}
}
return json_encode($response);
Here is my test file:
const assoc_cal = require('../../secure-htdocs/js/templates/association_calendar');
jest.mock('../../secure-htdocs/ajax/calendar_ajax.php');
test("loadTeams returns Teams 1 and 2 when passed clubID 34", () =>{
data = {action: "loadTeams", ClubID: 34};
const expected = [
{
name: "Team 1",
clubID: 34
},
{
name: "Team 2",
clubID: 34
}
];
expect(assoc_cal(data)).toEqual(expect.arrayContaining(expected));
});
But when I run my test, it still tries to call the real calendar_ajax.php file. I'm apparently setting up the mock incorrectly. Can anyone else out with this?

how can get content json from <scriptscript type="application/ld+json">

I can't find an API for Vine to get the page content's title, description and image. The JSON is in the body of the page itself in a script tag: . How do I get the content (the JSON) of this script tag using PHP so it can be parsed?
Vine page:
https://vine.co/v/igO3EbIXDlI
From page source
<script type="application/ld+json">
{
"#context": "http://schema.org",
"#type": "SocialMediaPosting",
"url": "https://vine.co/v/igO3EbIXDlI",
"datePublished": "2016-03-01T00:58:35",
"author": {
"#type": "Person",
"name": "MotorAddicts\u2122",
"image": "https://v.cdn.vine.co/r/avatars/39FEFED72B1242718633613316096_pic-r-1439261422661708f3e9755.jpg.jpg?versionId=LPjQUQ4KmTIPLu3iDbXw4FipgjEpC6fw",
"url": "https://vine.co/u/989736283540746240"
},
"articleBody": "Mmm... Black black blaaaaack!! \ud83d\ude0d ( Drift \u53d1 )",
"image": "https://v.cdn.vine.co/r/videos/98C3799A811316254965085667328_SW_WEBM_14567938452154dc600dbde.webm.jpg?versionId=wPuaQvDxnpwF7KjSGao21hoddooc3eCl",
"interactionCount": [{
"#type": "UserInteraction",
"userInteractionType": "http://schema.org/UserLikes",
"value": "1382"
}, {
"#type": "UserInteraction",
"userInteractionType": "http://schema.org/UserShares",
"value": "368"
}, {
"#type": "UserInteraction",
"userInteractionType": "http://schema.org/UserComments",
"value": "41"
}, {
"#type": "UserInteraction",
"userInteractionType": "http://schema.org/UserViews",
"value": "80575"
}],
"sharedContent": {
"#type": "VideoObject",
"name" : "Mmm... Black black blaaaaack!! \ud83d\ude0d ( Drift \u53d1 )",
"description" : "",
"thumbnailUrl" : "https://v.cdn.vine.co/r/videos/98C3799A811316254965085667328_SW_WEBM_14567938452154dc600dbde.webm.jpg?versionId=wPuaQvDxnpwF7KjSGao21hoddooc3eCl",
"uploadDate" : "2016-03-01T00:58:35",
"contentUrl" : "https://v.cdn.vine.co/r/videos_h264high/98C3799A811316254965085667328_SW_WEBM_14567938452154dc600dbde.mp4?versionId=w7ugLPYtj5LWeVUsXaH1bt2VuK8QE0qv",
"embedUrl" : "https://vine.co/v/igO3EbIXDlI/embed/simple",
"interactionCount" : "82366"
}
}
</script>
What to do after this?
$html = 'https://vine.co/v/igO3EbIXDlI';
$dom = new DOMDocument;
$dom->loadHTML($html);
When I go to that page, I don't see the script tag you are referencing. So I found a page that has one, and this is how I would do it:
<?php
$html = file_get_contents('https://tv-sewingcenter.com');
$dom = new DOMDocument;
libxml_use_internal_errors(true);
$dom->loadHTML($html);
$jsons = array();
$scripts = $dom->getElementsByTagName('script');
if( ! empty( $scripts ) )
{
foreach( $scripts as $script )
{
if( $script->hasAttribute('type') && $script->getAttribute('type') == 'application/ld+json' )
{
$jsons[] = json_decode($script->nodeValue, true);
}
}
if( ! empty( $jsons ) )
{
foreach( $jsons as $json )
{
echo '<pre>';
print_r( $json );
echo '</pre>';
}
}
}

Gauge Chart Values from Database

Instead of "value": "11413425.62", how can I change the code to get the data from database phpMyAdmin?
Here's my full code..
<script type="text/javascript" src="http://static.fusioncharts.com/code/latest/themes/fusioncharts.theme.fint.js?cacheBust=56"></script>
<script type="text/javascript">
FusionCharts.ready(function(){
var fusioncharts = new FusionCharts({
type: 'angulargauge',
renderAt: 'Profit10%',
width: '350',
height: '250',
dataFormat: 'json',
dataSource: {
"chart": {
"caption": "Total Profit",
"subcaption": "After add value",
"lowerLimit": "0",
"upperLimit": "10000000",
"showValue": "1",
"valueBelowPivot": "1",
"theme": "fint"
},
"colorRange": {
"color": [{
"minValue": "0",
"maxValue": "50000",
"code": "#e44a00"
}, {
"minValue": "50000",
"maxValue": "75000",
"code": "#f8bd19"
}, {
"minValue": "75000",
"maxValue": "100000",
"code": "#6baa01"
}]
},
"dials": {
"dial": [{
"value": "11413425.62"
}]
}
}
}
);
fusioncharts.render();
});
</script>
and the data had been extracted using this file "dataCountryGrossMargin.php" with this code.
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
//connect to the server
$connect= mysql_connect("127.0.0.1","root","");
//$conn = new mysqli($servername, $username, $password);
if(!$connect)
{
die('Could not connect: '.mysql_error($connect));
}
//connect to the database
mysql_select_db("fyp",$connect);
$result = mysql_query("SELECT Country, COGS FROM `table 3`");
$rows = array();
while($r = mysql_fetch_array($result)) {
$row[0] = $r[0];
$row[1] = $r[1];
array_push($rows,$row);
}
print json_encode($rows, JSON_NUMERIC_CHECK);
mysql_close($connect);
?>
Thank you !
You can use a similar approach to the example offered on the Fusioncharts website:
<?php
/* Include the `fusioncharts.php` file that contains functions to embed the charts. */
include("includes/fusioncharts.php");
/* The following 4 code lines contain the database connection information. Alternatively, you can move these code lines to a separate file and include the file here. You can also modify this code based on your database connection. */
$hostdb = "localhost"; // MySQl host
$userdb = "root"; // MySQL username
$passdb = ""; // MySQL password
$namedb = "fusioncharts_phpsample"; // MySQL database name
// Establish a connection to the database
$dbhandle = new mysqli($hostdb, $userdb, $passdb, $namedb);
/*Render an error message, to avoid abrupt failure, if the database connection parameters are incorrect */
if ($dbhandle->connect_error) {
exit("There was an error with your connection: ".$dbhandle->connect_error);
}
?>
<html>
<head>
<title>FusionCharts XT - Column 2D Chart - Data from a database</title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<!-- You need to include the following JS file to render the chart.
When you make your own charts, make sure that the path to this JS file is correct.
Else, you will get JavaScript errors. -->
<script src="fusioncharts/fusioncharts.js"></script>
</head>
<body>
<?php
// Form the SQL query that returns the top 10 most populous countries
$strQuery = "SELECT Name, Population FROM Country ORDER BY Population DESC LIMIT 10";
// Execute the query, or else return the error message.
$result = $dbhandle->query($strQuery) or exit("Error code ({$dbhandle->errno}): {$dbhandle->error}");
// If the query returns a valid response, prepare the JSON string
if ($result) {
// The `$arrData` array holds the chart attributes and data
$arrData = array(
"chart" => array(
"caption" => "Top 10 Most Populous Countries",
"paletteColors" => "#0075c2",
"bgColor" => "#ffffff",
"borderAlpha"=> "20",
"canvasBorderAlpha"=> "0",
"usePlotGradientColor"=> "0",
"plotBorderAlpha"=> "10",
"showXAxisLine"=> "1",
"xAxisLineColor" => "#999999",
"showValues" => "0",
"divlineColor" => "#999999",
"divLineIsDashed" => "1",
"showAlternateHGridColor" => "0"
)
);
$arrData["data"] = array();
// Push the data into the array
while($row = mysqli_fetch_array($result)) {
array_push($arrData["data"], array(
"label" => $row["Name"],
"value" => $row["Population"]
)
);
}
/*JSON Encode the data to retrieve the string containing the JSON representation of the data in the array. */
$jsonEncodedData = json_encode($arrData);
/*Create an object for the column chart using the FusionCharts PHP class constructor. Syntax for the constructor is ` FusionCharts("type of chart", "unique chart id", width of the chart, height of the chart, "div id to render the chart", "data format", "data source")`. Because we are using JSON data to render the chart, the data format will be `json`. The variable `$jsonEncodeData` holds all the JSON data for the chart, and will be passed as the value for the data source parameter of the constructor.*/
$columnChart = new FusionCharts("column2D", "myFirstChart" , 600, 300, "chart-1", "json", $jsonEncodedData);
// Render the chart
$columnChart->render();
// Close the database connection
$dbhandle->close();
}
?>
<div id="chart-1"><!-- Fusion Charts will render here--></div>
</body>
</html>

Save created row in datatable editor via php

I using datatable editor to display rows
This is the code i'm using
var editor;
$(document).ready( function () {
editor = new $.fn.dataTable.Editor( {
"ajaxUrl": {
"create": "admin/save",
},
"domTable": "#example",
"fields": [ {
"label": "username:",
"name": "username"
}, {
"label": "password:",
"name": "password",
"type":"password"
}, {
"label": "fname:",
"name": "fname"
}, {
"label": "lname:",
"name": "lname"
}, {
"label": "email:",
"name": "email"
},{
"label": "address:",
"name": "address"
}
]
} );
$('#example').dataTable( {
"sDom": "Tfrtip",
"aoColumns": [
{ "mData": "username"},
{ "mData": "password" },
{ "mData": "fname" },
{ "mData": "lname" },
{ "mData": "email" },
{ "mData": "address" }
],
"oTableTools": {
"sRowSelect": "single",
"aButtons": [
{ "sExtends": "editor_create", "editor": editor },
{ "sExtends": "editor_edit", "editor": editor },
{ "sExtends": "editor_remove", "editor": editor }
]
}
} );
} );
How can I pass the form data to controller page.I also given name field but it is not added to element.
create : admin/save
Here admin is the controller name and save is the action name.
Please help me.
Using Datatables with the Editor extension, it sends data to the server to be processed. The client sends three fields: action, id and data. The action can be create, edit or delete. The id is only filled in for edit.
So in short, you can use this controller:
<?php
namespace MyModule\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\JsonModel;
class DatatablesController extends AbstractActionController
{
public function saveAction()
{
if (!$this->getRequest()->isPost()) {
$response = $this->getResponse();
$response->setStatusCode(405); // Method not allowed
return $response;
}
$action = $this->params()->fromPost('action', null);
$data = array();
switch ($action) {
case 'create':
$data = $this->createRow();
break;
case 'edit':
$data = $this->editRow();
break;
case 'delete':
$data = $this->deleteRow();
break;
default:
$response = $this->getResponse();
$response->setStatusCode(422); // Unprocessable entity
return $response;
}
$model = new JsonModel($data);
return $model;
}
protected function createRow()
{
$data = $this->params()->fromPost('data', array());
// Create a new entity with $data
// Return the properties from the new entity
return array();
}
protected function editRow()
{
$id = $this->params()->fromPost('id');
$data = $this->params()->fromPost('data', array());
// Fetch the entity with id $id
// Update the entity with $data
// Return the properties from the entity
return array();
}
protected function deleteRow()
{
$ids = $this->params()->fromPost('data', array());
// Remove all entities with an id in the array $ids
}
}

Categories