inline keyboard button make action change user url using php? - javascript

i have a php code for telegram bot inline keyboard i want when i press one of the two buttons
i want to redirect the user to another page, look at my code is working but i dont know how to do this action on the inline keyboard
if ($telegram == "on"){
$keyboard = json_encode([
"inline_keyboard" => [
[
[
"text" => "✅ ADMINPAGE ✅",
"callback_data" => "callbackone"
],
[
"text" => "❌ HOMEPAGE ❌",
"callback_data" => "callbacktwo"
],
]
]
]);
$parameters = array(
"chat_id" => $chat_id,
"text" => $txt,
'reply_markup' => $keyboard
);
$send = ($parameters);
$website_telegram = "https://api.telegram.org/bot{$bot_url}";
$ch = curl_init($website_telegram . '/sendMessage');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($send));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
}

The InlineKeyboardButton accepts an url parameter:
url
Optional. HTTP or tg:// URL to be opened when the button is pressed.
Links tg://user?id=<user_id> can be used to mention a user by their ID without using a username, if this is allowed by their privacy settings.
So you'll need something like:
$keyboard = json_encode([
"inline_keyboard" => [
[
[
"text" => "✅ ADMINPAGE ✅",
"url" => "https://example.com/admin"
],
[
"text" => "❌ HOMEPAGE ❌",
"url" => "https://example.commin"
]
]
]
]);

Related

How to get url with javascript and pass it to php as a variable

I have code to get some data (terms = page-a) built with Wordpress.
Currently, the data of page-a is acquired like'terms' =>'page-a' and displayed on the example.com/page-a page.
I would like to change this data acquisition code so that the data along the lower page url can be acquired (for example, the data on page-b at example.com/page-b).
I created a code to get the url with $_SERVER and convert it, but I can't get the url because I am using ajax. I want to get the url with javascript and pass it to php.
How should I make the changes?
functions.php
add_action('wp_ajax_get_case', 'dk_get_case');
add_action('wp_ajax_nopriv_get_case', 'dk_get_case');
function dk_get_case() {
$headers['Access-Control-Allow-Origin'] = '*';
$return = ['status' => false, 'data' => [], 'message' => ''];
$case_clinics = [1,2,3,4];
foreach($case_clinics as $key => $case_clinic){
// (1)Get the current URL
$http = is_ssl() ? 'https' : 'http' . '://';
$url = $http . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];
// (2)Get a string such as'page-a' from the URL
$keys = parse_url($url);
$path = explode("/", $keys['path']);
$terms = $path[2];
$dk_posts = get_posts(
array(
'showposts' => -1,
'post_type' => 'case',
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'case_clinic',
'field' => 'term_id',
'terms' => $case_clinic
),
array(
'taxonomy' => 'case_category',
'field' => 'slug',
'terms' => 'page-a'
)
)
)
);
taxonomy-case_category-page-a.php
<div class="col case-right">
<h3 style="font-family:'Futura PT'; font-weight:600">Clinic</h3>
<h4 style="font-weight:600">Clinic</h4>
                                            //data display position
<div class="case-img" data-slider-3></div>
<div class="popup"></div>
</div>
Tried
footer.php
<script>
jQuery(document).ready(function () {
var url = window.location.href;
$.ajax({
type: "GET",
url: "taxonomy-case_category-page-a.php",
data: {"url": url},
});
});
taxonomy-case_category-page-a.php
<?php var_dump($_GET['url']); ?>
error
GET: 404error
https://example.com/pagea/taxonomy-case_category-page-a.php?url=https%3A%2F%2Fcharme-beauty.jp%2Fstaging%2Fcase%2Fpagea%2F

Display WordPress last posts via AJAX

I am building a news blog that upload posts every hour. I have created a shortcode that displays the last 15 posts on the home page. My problem was that the server cache needed to be deleted every hour. so I've decided to serve the post via AJAX so this area will get the latest posts every page load.
I found this answer and combine it whit my code.
My problem is that it displays all of the posts and not just 15.
PHP:
function get_ajax_posts() {
// Query Arguments
$args = array(
'post_type' => array('post'),
'post_status' => array('publish'),
'posts_per_page' => 15,
'nopaging' => true,
'order' => 'DESC',
'orderby' => 'date',
);
$ajaxposts = new WP_Query( $args );
$response = '';
if ( $ajaxposts->have_posts() ) {
while ( $ajaxposts->have_posts() ) {
$ajaxposts->the_post();
$response .= get_template_part( 'template-parts/content-archive');
}
} else {
$response .= get_template_part('none');
}
echo $response;
exit; // leave ajax call
}
// Fire AJAX action for both logged in and non-logged in users
add_action('wp_ajax_get_ajax_posts', 'get_ajax_posts');
add_action('wp_ajax_nopriv_get_ajax_posts', 'get_ajax_posts');
JS:
$.ajax({
type: 'POST',
url: '<?php echo admin_url('admin-ajax.php');?>',
dataType: "html",
data: { action : 'get_ajax_posts' },
success: function( response ) {
$( '.home-hot-flights' ).html( response );
//hot-flights
var hot_flights_item = $(".home-hot-flights article").width() + 17;
$(".art-move-left").click(function () {
$('.move-right').addClass('show-move-right');
var leftPos = $('.home-hot-flights').scrollLeft();
$(".home-hot-flights").animate({scrollLeft: leftPos - hot_flights_item}, 200);
});
$(".art-move-right").click(function () {
var leftPos = $('.home-hot-flights').scrollLeft();
$(".home-hot-flights").animate({scrollLeft: leftPos + hot_flights_item}, 200);
});
}
});
This might help you:
Pagination parameters
(nopaging (boolean) – show all posts or use pagination. Default value
is ‘false’, use paging. )
Display all posts by disabling pagination:
$query = new WP_Query( array( 'nopaging' => true ) );
I think you should remove that parameter if you want to display a certain number of posts using posts_per_page.
Try this piece of code I have edit your code please see below
function get_ajax_posts() {
// Query Arguments
$args = array(
'post_type' => array('post'),
'post_status' => array('publish'),
'posts_per_page' => 15,
'order' => 'DESC',
'orderby' => 'date',
);
wp_reset_query();
$ajaxposts = new WP_Query( $args );
$response = '';
if ( $ajaxposts->have_posts() ) {
while ( $ajaxposts->have_posts() ) {
$ajaxposts->the_post();
$response .= get_template_part( 'template-parts/content-archive');
}
} else {
$response .= get_template_part('none');
}
echo $response;
exit; // leave ajax call
}
// Fire AJAX action for both logged in and non-logged in users
add_action('wp_ajax_get_ajax_posts', 'get_ajax_posts');
add_action('wp_ajax_nopriv_get_ajax_posts', 'get_ajax_posts');
If the two loops data is overwridden then, I your first code wp_reset_query() is incorrect. If you are using WP_Query then
wp_reset_postdata() //remove wp_reset_query() which is used for wp_query()
should be used after the end of the WHILE loop which means that in your two loops you have to have
wp_reset_postdata() // use this at both loops

Yii2-Working with multiple check boxes in gridview

I have a gridview in which there also a checkbox.
<?= Html::a('Disconnect', ['dco'], ['class' => 'btn btn-success', 'id'=>'dco']) ?>
<?= Html::a('Connect', ['rco'], ['class' => 'btn btn-info','id'=>'rco']) ?>
<?php Pjax::begin(); ?>
<div class="pre-scrollable">
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\CheckboxColumn', 'checkboxOptions' => function($d) {
return ['value' => $d['msn']];
}],
'customer_id',
'dept_name:ntext',
'sub_div_name',
'division_name',
'allowed_units',
'msn',
'units_consumed',
[
'label' => 'Disconnected',
'attribute' => 'disconnected',
'format'=>'raw',
'contentOptions' => ['style'=>'text-align:center'],
'value' => function($model){
return $model->disconnected == 1 ? '<span class="glyphicon glyphicon-ok text-success"></span>' : '<span class="glyphicon glyphicon-remove text-danger"></span>';
},
'filter' => Html::activeDropDownList($searchModel, 'disconnected', [''=>'All','1'=>'Yes','0'=>'No'], ['class' => 'form-control']),
],
'active_energy_total_m',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
</div>
I am using ajax for sending checked data to the controller.
There is two buttons Disconnect and Connect. On the checkbox checked and after clicking any of the two buttons, the corresponding selected item will be connected or disconnected.
$DCOurl = Url::toRoute(['/hescolog/dco']);
$RCOurl = Url::toRoute(['/hescolog/rco']);
$(document).ready(function () {
//DCO
$('#dco').on('click',function(e) {
e.preventDefault();
var strValue = "";
$('input[name="selection[]"]:checked').each(function() {
if(strValue!=="")
{
strValue = strValue + " , " + this.value;
}
else
strValue = this.value;
});
// alert(strValue);
$.ajax({
url: '$DCOurl',
type: 'POST',
dataType: 'json',
data: {data:strValue},
success: function(data) {
alert(data);
}
});
});
$('#rco').on('click',function(e) {
e.preventDefault();
var strValue = "";
$('input[name="selection[]"]:checked').each(function() {
if(strValue!=="")
{
strValue = strValue + " , " + this.value;
}
else
strValue = this.value;
});
// alert(strValue);
$.ajax({
url: '$RCOurl',
type: 'POST',
dataType: 'json',
data: {data:strValue},
success: function(data) {
alert(data);
}
});
});
});
Controller
if(Yii::$app->request->isAjax && Yii::$app->request->post())
{
$data = explode(',',$_POST['data']);
foreach($data as $value)
{
//...... other code
}
}
Now the problem I am facing is when I check all the checkboxes and click on any of the buttons, only the 1st checkbox checked an item is connect or disconnect.
Although while checking the controller `` I can see both the items against checkbox checked.
array(2) { [0]=> string(13) "002995000100 " [1]=> string(13) " 002992002018" }
Update 1
Against these two buttons, I have a SOAP service
if(Yii::$app->request->isAjax && Yii::$app->request->isPost)
{
$data = explode(',',$_POST['data']);
foreach($data as $value)
{
$ic++;
$msn = $value;
$xml_post_string = /** #lang text */
'<soapenv:Envelope
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:soap="http://soap.inf.hexing.cn">
<soapenv:Header/>
<soapenv:Body>
<soap:doCommand>
<!--Optional:-->
<arg0><![CDATA[<?xml version="1.0" encoding="utf-8"?>
<RequestMessage
xmlns="http://iec.ch/TC57/2011/schema/message"
xmlns:m="http://iec.ch/TC57/2011/EndDeviceControls#"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://iec.ch/TC57/2011/schema/message
Message.xsd">
<Header>
<Verb>create</Verb>
<Noun>EndDeviceControls</Noun>
<Revision>2.0</Revision>
<Timestamp>2016-01-01T00:00:00+04:30</Timestamp>
<Source>MDM</Source>
<AsyncReplyFlag>true</AsyncReplyFlag>
<ReplyAddress>http://ip:port/AmiWeb/services/Metering</ReplyAddress>
<AckRequired>true</AckRequired>
<User>
<UserID>'.$userName.'</UserID>
</User>
<MessageID>83c643e6-85c5-43c0-9e0a-fa1deb469b72</MessageID>
<CorrelationID>1001</CorrelationID>
<Property>
<Name>password</Name>
<Value>'.$password.'</Value>
</Property>
<Property>
<Name>timeout(m)</Name>
<Value>30</Value>
</Property>
</Header>
<Payload>
<m:EndDeviceControls>
<m:EndDeviceControl>
<m:reason>Disconnect/Reconnect</m:reason>
<m:EndDeviceControlType ref="3.0.211.23"/>
<m:EndDevices>
<m:mRID>'.$msn.'</m:mRID>
<m:Names>
<m:name>Disconnect</m:name>
<m:NameType>
<m:name>ControlType</m:name>
</m:NameType>
</m:Names>
</m:EndDevices>
</m:EndDeviceControl>
</m:EndDeviceControls>
</Payload>
</RequestMessage>
]]></arg0>
</soap:doCommand>
</soapenv:Body>
</soapenv:Envelope>';
$headers = array(
"Content-type: text/xml;charset=\"utf-8\"",
"Accept: text/xml",
"Cache-Control: no-cache",
"Pragma: no-cache",
"Content-length: ".strlen($xml_post_string),
); //SOAPAction: your op URL
$url = $soapUrl;
// PHP cURL for https connection
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//curl_setopt($ch, CURLOPT_USERPWD, $soapUser.":".$soapPassword); // username and password - declared at the top of the doc
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_post_string); // the SOAP request
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// converting
$response = curl_exec($ch);
curl_close($ch);
$domd=new DOMDocument();
if(!$domd->loadXML($response)){
throw new \RuntimeException("failed to parse XML!");
}
$inner_xml=$domd->getElementsByTagName("return")->item(0)->textContent;
if(!($domd2=#DOMDocument::loadXML($inner_xml))){
throw new \RuntimeException("failed to parse inner_xml!");
}
$AsyncReplyFlag=$domd2->getElementsByTagName("AsyncReplyFlag")->item(0)->textContent;
if ($AsyncReplyFlag =='true')
{
$ds = 1;
$disconnected_at = date('Y-m-d H:i:s');
try {
Yii::$app->db->createCommand(/** #lang text */
"update
`accurate_mam`.`daily_log`
set
`disconnected` = '$ds',
`diconnected_at` = '$disconnected_at',
`reconnected_at` = NULL
where `msn` = '$msn' ;
")->execute(); //update master table
Yii::$app->db->createCommand(/** #lang text */
"update
`accurate_mam`.`log_disconnected`
set
`disconnected_at` = '$disconnected_at'
where `msn` = '$msn'")->execute();// update log disconnected table
} catch (Exception $e) {
} // updating the master table
}
}
}
I don't know what is the issue and why I am not able to process both the records.
Any help would be highly appreciated.
Because you left a comment here, I used the beginForm method:
in View
<div class="pre-scrollable">
<?php Pjax::begin() ?>
<?=Html::beginForm(['test'],'post');?>
<?= Html::submitButton('Disconnect', ['class' => 'btn btn-success', 'name'=>'dco', 'value'=>'dco', 'id'=>'dco','style'=>'margin:0 10px;']) ?>
<?= Html::submitButton('Connect', ['class' => 'btn btn-primary', 'name'=>'rco', 'value'=>'rco','id'=>'rco']) ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\CheckboxColumn', 'checkboxOptions' => function($d) {
return ['value' => $d['msn']];
}],
'customer_id',
'dept_name:ntext',
'sub_div_name',
'division_name',
'allowed_units',
'msn',
'units_consumed',
[
'label' => 'Disconnected',
'attribute' => 'disconnected',
'format'=>'raw',
'contentOptions' => ['style'=>'text-align:center'],
'value' => function($model){
return $model->disconnected == 1 ? '<span class="glyphicon glyphicon-ok text-success"></span>' : '<span class="glyphicon glyphicon-remove text-danger"></span>';
},
'filter' => Html::activeDropDownList($searchModel, 'disconnected', [''=>'All','1'=>'Yes','0'=>'No'], ['class' => 'form-control']),
],
'active_energy_total_m',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
<?= Html::endForm();?>
<?php Pjax::end() ?>
</div>
in controllers
public function actionTest()
{
$searchModel = \Yii::createObject(\app\models\TestSearch::className());
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
if ( Yii::$app->request->post() ) {
$arr_select=(array)Yii::$app->request->post('selection'); //An array of selected items (checkbox)
$dco=Yii::$app->request->post('dco'); // submitButton Disconnect
$rco=Yii::$app->request->post('rco'); // submitButton Connect
if ($dco === 'dco') {
//code for Disconnect here ($query)
// example: $modelTest::updateAll(['disconnected' => 1], ['msn' => $arr_select]);
} elseif ($rco == 'rco') {
//code for Connect here ($query)
}
}
return $this->render('test', [
'dataProvider' => $dataProvider,
'searchModel' => $searchModel,
]);
}
You can optimize your code in the controller.
Of course, I think if you use the following method, it is better (a button and ...).
You can easily decide on the controller.
<?= Html::dropDownList('action','',[ 'Connect' =>'Connect','Disconnect' =>'Disconnect'],['prompt' => 'Please select','class'=> 'field-black input-sm']) ?>
<?= Html::submitButton('Apply', ['class' => 'btn btn-success','style'=>'margin:0 10px;']) ?>
You can place the above code instead of the two submitButton. Then decide on the controller according to the dropDownList value. Like below:
also add:, 'data-pjax'=>''
$_action=Yii::$app->request->post('action'); // dropDown
$arr_select=(array)Yii::$app->request->post('selection'); //selected items

Yii2 Kartik FileUpload : Multiupload initialPreviewConfig JSON data from controller seems doesnt work

Before all
I have model for image as simple as
return [
'id' => 'ID',
'parent_id' => 'Parent ID',
'photo' => 'Photo', <= just for filename
];
the case is
Create Parent model then save then redirect to form for uploading images related to its parent.
all uploading function work proprerly but no with delete function
This is my upload image form
echo FileInput::widget([
'model' => $photo,
'attribute' => 'photo',
'options'=>[
'accept'=>'image/*',
'multiple'=>true
],
'pluginOptions' => [
'uploadUrl' => Url::to(['/controller/upload', 'id'=> $parent->id]),
'initialPreview'=>$pre-initViews-data,
'initialPreviewAsData'=>true,
'initialCaption'=>"Foto Tersangka",
'initialPreviewConfig' => $pre-initConfigs-data,
'overwriteInitial'=>true,
//'deleteUrl'=> Url::to(['/controller/deletephoto']), <= case 2
'showPreview' => true,
'showRemove' => false,
'showUpload' => false,
'maxFileSize'=>2800
],
'pluginEvents' => [
'fileuploaded'=>"function(event, data, previewId, index){
console.log(data);
}",
]
]);
And here my controller side
$imageFile = UploadedFile::getInstance($model, 'photo');
$directory = Yii::$app->basePath. '/images/';
if ($imageFile) {
$fileName = Yii::$app->security->generateRandomString(). '.' . $imageFile->extension;
$filePath = $directory . $fileName;
if ($imageFile->saveAs($filePath) && $model->save(false)) {
$path = '/images/temp/' . $fileName;
Image::thumbnail($directory.$fileName, 120, 120)
->save(Yii::$app->basePath.$path, ['quality' => 80]);
$response = [];
$reponse['initialPreview'] = \Yii::$app->request->BaseUrl.'/images/'.$fileName;
$reponse['initialPreviewConfig']=[
'caption'=>'',
'width'=>'90px',
'key'=>$model->id,
'url'=>Url::to(['/controller/deletephoto']),
'extra'=>['id'=>$model->id]
];
echo json_encode($reponse);
}
}
And will produce JSON data like this :
{
"initialPreview": "\/web\/images\/Kl1IJOabLs5ENzzgkuW8ln_TILcDumy9.png",
"initialPreviewConfig": {
"caption": "",
"width": "90px",
"key": 38,
"url": "\/web\/index.php?r=controller%2Fdeletephoto",
"extra": {
"id": 38
}
}
}
The issue
I try different way like :
case 1 :
at form widget withoud pluginOptions => deleteUrl'=> Url::to(['/controller/deletephoto']),
upload process success, response from controller initialPreview overwriting initial as expected, but initialPreviewConfig seems doesnt fit, so delete button doesnt work/ doesnt give any process when clicked.
case 2 :
at form widget with pluginOptions => deleteUrl'=>
Url::to(['/controller/deletephoto']) , upload process as expected, but when i click delete button post action didnt parse key as below
Query string
r : controller/deletephoto
Form data
key : {empty key}
Finally
Ive spend huge amount of hours, Please review my code, is there something wrong?
a Big thanks for your help.
UPDATE ISSUE RESOLVED
after long hours finally i got the way..
replace
$response = [];
$reponse['initialPreview'] = \Yii::$app->request->BaseUrl.'/images/'.$fileName;
$reponse['initialPreviewConfig']=[
'caption'=>'',
'width'=>'90px',
'key'=>$model->id,
'url'=>Url::to(['/controller/deletephoto']),
'extra'=>['id'=>$model->id]
];
echo json_encode($reponse);
with
return Json::encode([
'initialPreview' => \Yii::$app->request->BaseUrl.'/images/'.$fileName,
'initialPreviewConfig' => [
[
'caption'=>'',
'width'=>'90px',
'key'=>$model->id,
'url'=>Url::to(['/controller/deletephoto']),
'extra'=>['id'=>$model->id]
],
],
]);
dont know why this happen,

Google Charts and JSON data

I'm not a JS guy, I working on a small interface for my weather station. I have a serverside code which generates the JSON data for the graph. It looks like this:
[
{
"temperature": "32.1",
"humidity": "91",
"battery": "100",
"time": "2016-02-21 15:28:56"
},
{
"temperature": "32.1",
"humidity": "99.3",
"battery": "100",
"time": "2016-02-21 15:28:47"
},
{
"temperature": "22.2",
"humidity": "70.2",
"battery": "88.2",
"time": "2016-02-21 15:28:19"
},
{
"temperature": "21.2",
"humidity": "88.1",
"battery": "90.4",
"time": "2016-02-21 15:28:22"
}
]
How can I feed this data into a Line chart using Google's Chart API? I have tried using the example but it does not work. (https://developers.google.com/chart/interactive/docs/gallery/linechart)
First define your array in the format which google charts requires:
$resultsarray = array(
'cols' => array(
array('label' => 'temperature', 'type' => 'number'),
array('label' => 'humidity', 'type' => 'number'),
array('label' => 'battery', 'type' => 'number'),
array('label' => 'time', 'type' => 'date'),
),
'rows' => array()
);
Then add the data to your array:
$resultsarray['rows'][] = array('c' => array( array('v'=> 'tempvalue'), array('v'=>'humidityval'), array('v'=>'batteryval'),array('v'=>'timeval')));
Encode as JSON and write to a file:
$fp = fopen('data.json', 'w');
//JSON encode and write array to file
fwrite($fp, json_encode($resultsarray, JSON_NUMERIC_CHECK));
fclose($fp);
Then in your JavaScript you need: (as per Google Example)
function drawChart() {
var jsonData = $.ajax({
url: "getData.php",
dataType: "json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
Then the contents of getdata.php (as per google example)
<?php
// This is just an example of reading server side data and sending it to the client.
// It reads a json formatted text file and outputs it.
$string = file_get_contents("data.json");
echo $string;
// Instead you can query your database and parse into JSON etc etc
?>
The json isn't formatted properly. Google charts expect a specific json type for its chart. I'm assuming that your database is mysql. If not, I can always modify the following code. I have created a small library to perform these annoying tasks. So here it is :
<?php
function generate_GChart_cols($result) {
$fieldcount = mysqli_num_fields($result);
$stringVal = [253]; // MySQL field type codes -See http://php.net/manual/en/mysqli-result.fetch-field-direct.php
$numericVal = [246, 8]; // MySQL field type codes -See http://php.net/manual/en/mysqli-result.fetch-field-direct.php
$colsarray = array();
for ($i = 0; $i < $fieldcount; $i++) {
$finfo = mysqli_fetch_field_direct($result, $i);
switch ($finfo->type) {
case in_array($finfo->type, $stringVal):
$type = 'string';
break;
case in_array($finfo->type, $numericVal):
$type = 'number';
break;
default:
$type = 'string';
}
// Constructs the column array
$colsarray[] = array(
'label' => $finfo->name,
'type' => $type
);
}
return $colsarray;
}
function generate_GChart_rows($result) {
$fieldcount = mysqli_num_fields($result);
$rows = array();
while ($r = $result->fetch_row()) {
$temp = array();
for ($j = 0; $j < $fieldcount; $j++) {
$temp[] = array(
'v' => $r[$j]
);
}
$rows[] = array(
'c' => $temp
);
};
return $rows;
}
?>
A usage example would be :
<?php
header('content-type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin:*'); //Include this header to make the requests cross-origin
include 'dbconnect.php';
include 'generate_google_json.php';
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = // Your query here - e.g SELECT * FROM TABLE // ;
$result = $conn->query($sql);
$table['data']['rows'] = generate_GChart_rows($result); // Call to function to generate rows
$table['data']['cols'] = generate_GChart_cols($result); // Call to function to generate columns
$conn->close(); // Close db connection
// We echo the json and enforce a numeric check on the values
echo $_GET['callback'] . '(' . json_encode($table, JSON_NUMERIC_CHECK) . ')';
?>
An example output would be :
?(
{
data:{
rows:[
{
c:[
{
v:3123600
},
{
v:3116452
}
]
}
],
cols:[
{
label:2013,
type:"number"
},
{
label:2014,
type:"number"
}
]
}
}
)
In the event where you use other types than bigint, varchart and decimal, you might wanna add more values to the $stringVal and $numericVal arrays :)
Cheers
Google charts is expecting the JSON in this format:
{
"cols": [
{"id":"","label":"temperature","pattern":"","type":"number"},
{"id":"","label":"humidity","pattern":"","type":"number"},
{"id":"","label":"battery","pattern":"","type":"number"},
{"id":"","label":"time","pattern":"","type":"date"}
],
"rows": [
{"c":[{"v":"32.1","f":null},{"v":99.3,"f":null},{"v":100,"f":null},{"v":2016-02-21 15:28:47,"f":null}]}
]
}

Categories