how to update variable dynamically of currency rate WITH php/json/ajax - php

I would like to know how to update variable dynamically of currency rate WITH php/AJAX/json that $CurrencyValue (the currency value from yahoo finance) will update only if the variable is different than it was before.
For example:
on 01/01/2016 10:00 USDINR gate was 67.454.
1/01/2016 10:01 USDINR gate was 67.104 (the variable $CurrencyValue be updated).
1/01/2016 10:02 gate of USDINR remains 67.104 (the variable $CurrencyValue not be updated).
1/01/2016 10:03 USDINR gate was 67.024 (so the variable $CurrencyValue be updated).
It is important the page will not refreshed, only the variable $CurrencyValue also if the variable changed I would like to get The exact date.
<?php
$from = 'USD'; $to = 'INR'; $url = 'http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s='. $from . $to .'=X'; $currencyValue = 0; $handle = fopen($url, 'r'); if ($handle) {
while (($data = fgetcsv($handle, 1024, ',', '"')) !== FALSE)
{
$currencyValue = $data[1];
}
fclose($handle);
} $date = date('l jS \of F Y h:i:s A');
?>
Value of 1 USDINR is <?php echo $currencyValue. ' - ' .$date; ?>
Thank you
EDIT
I have a code of euro-dollar exchange via YAHOO FINANCE works with PHP / AJAX. My question is how to integrate the data released chart works with CHARTS.JS
labels: ["2016-06-02 12:41:06", "2016-06-02 12:41:08"],
datasets: [{
label: "My Third dataset - No bezier",
data: [1.1200,1.1205],
lineTension: 0,
fill: false,
}]
{"rate":"1.1200","time":"2016-06-02 12:41:06"}
{"rate":"1.1205","time":"2016-06-02 12:41:08"}
{"rate":"1.1199","time":"2016-06-02 12:41:10"}
{"rate":"1.1199","time":"2016-06-02 12:41:12"}
The Code:
<script src="Chart.bundle.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<style>
canvas {
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
}
</style>
<?php
if(isset($_GET['fetchOnly'])){
$from = 'eur';
$to = 'usd';
$url = 'http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s='. $from . $to .'=X';
$response = array();
$handle = fopen($url, 'r');
if ($handle) {
while (($data = fgetcsv($handle, 1024, ',', '"')) !== FALSE)
{
$response['rate'] = $data[1];
$response['time'] = date("Y-m-d H:i:s");
}
fclose($handle);
}
echo json_encode($response);
die();
}
?>
<div id="responseText"></div>
<script>
// run the function, it will re-run itself
fetchRate();
function fetchRate() {
// create the new AJAX Object
xmlhttp = new XMLHttpRequest();
// this handles the request
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
// if the request came back successfully
if(xmlhttp.status == 200){
// write the response to a div
div = document.getElementById("responseText")
div.innerHTML = div.innerHTML + '<br />'+ xmlhttp.responseText;
}else{
// if the request had an error
div.innerHTML = div.innerHTML + '<br />Error fetching rates error code : '+xmlhttp.status;
}
// rerun this function to fetch updates
setTimeout(fetchRate,1000);
}
};
// open the AJAX Object
xmlhttp.open("GET", "<?= basename(__FILE__) ?>?fetchOnly", true);
// send the AJAX request
xmlhttp.send();
}
</script>
<div style="width:100%;">
<canvas id="canvas"></canvas>
</div>
<script>
var MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var randomScalingFactor = function() {
return Math.round(Math.random() * 100 * (Math.random() > 0.5 ? -1 : 1));
};
var randomColorFactor = function() {
return Math.round(Math.random() * 255);
};
var randomColor = function(opacity) {
return 'rgba(' + randomColorFactor() + ',' + randomColorFactor() + ',' + randomColorFactor() + ',' + (opacity || '.3') + ')';
};
var config = {
type: 'line',
data: {
labels: ["2016-06-02 12:36:05", "2016-06-02 12:37:05"],
datasets: [{
label: "My Third dataset - No bezier",
data: [1,2],
lineTension: 0,
fill: false,
}]
},
options: {
responsive: true,
legend: {
position: 'bottom',
},
hover: {
mode: 'label'
},
scales: {
xAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Month'
}
}],
yAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Value'
}
}]
},
title: {
display: true,
text: 'Chart.js Line Chart - Legend'
}
}
};
$.each(config.data.datasets, function(i, dataset) {
var background = randomColor(0.5);
dataset.borderColor = background;
dataset.backgroundColor = background;
dataset.pointBorderColor = background;
dataset.pointBackgroundColor = background;
dataset.pointBorderWidth = 1;
});
window.onload = function() {
var ctx = document.getElementById("canvas").getContext("2d");
window.myLine = new Chart(ctx, config);
};
$('#randomizeData').click(function() {
$.each(config.data.datasets, function(i, dataset) {
dataset.data = dataset.data.map(function() {
return randomScalingFactor();
});
});
window.myLine.update();
});
$('#addDataset').click(function() {
var background = randomColor(0.5);
var newDataset = {
label: 'Dataset ' + config.data.datasets.length,
borderColor: background,
backgroundColor: background,
pointBorderColor: background,
pointBackgroundColor: background,
pointBorderWidth: 1,
fill: false,
data: [],
};
for (var index = 0; index < config.data.labels.length; ++index) {
newDataset.data.push(randomScalingFactor());
}
config.data.datasets.push(newDataset);
window.myLine.update();
});
$('#addData').click(function() {
if (config.data.datasets.length > 0) {
var month = MONTHS[config.data.labels.length % MONTHS.length];
config.data.labels.push(month);
$.each(config.data.datasets, function(i, dataset) {
dataset.data.push(randomScalingFactor());
});
window.myLine.update();
}
});
$('#removeDataset').click(function() {
config.data.datasets.splice(0, 1);
window.myLine.update();
});
$('#removeData').click(function() {
config.data.labels.splice(-1, 1); // remove the label first
config.data.datasets.forEach(function(dataset, datasetIndex) {
dataset.data.pop();
});
window.myLine.update();
});
</script>
Thank you.

<?php
if(isset($_GET['fetchOnly'])){
$from = 'USD';
$to = 'INR';
$url = 'http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s='. $from . $to .'=X';
$response = array();
$handle = fopen($url, 'r');
if ($handle) {
while (($data = fgetcsv($handle, 1024, ',', '"')) !== FALSE)
{
$response['rate'] = $data[1];
$response['date'] = $data[2];
$response['time'] = $data[3];
}
fclose($handle);
fclose($handle);
}
echo json_encode($response);
die();
}
?>
<div id="responseText"></div>
<script>
// run the function, it will re-run itself
fetchRate();
function fetchRate() {
// create the new AJAX Object
xmlhttp = new XMLHttpRequest();
// this handles the request
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
// if the request came back successfully
if(xmlhttp.status == 200){
// write the response to a div
div = document.getElementById("responseText")
div.innerHTML = div.innerHTML + '<br />'+ xmlhttp.responseText;
}else{
// if the request had an error
div.innerHTML = div.innerHTML + '<br />Error fetching rates error code : '+xmlhttp.status;
}
// rerun this function to fetch updates
setTimeout(fetchRate,3000);
}
};
// open the AJAX Object
xmlhttp.open("GET", "<?= basename(__FILE__) ?>?fetchOnly", true);
// send the AJAX request
xmlhttp.send();
}

Related

CodeIgniter AJAX JSON validator with form validation

I am trying to make AJAX form validation work in CodeIgniter.
If you have the same title don't add The data from the form always reports as successful, even if the result is negative.
Is there a mistake in my logic?
Save controller:
public function save(){
$options = array();
$data['title'] = $this->input->post('title');
$data['description'] = $this->input->post('description');
$data['sale_price'] = $this->input->post('sale_price');
$data['purchase_price'] = $this->input->post('purchase_price');
$data['add_timestamp'] = time();
$data['options'] = json_encode($options);
$this->form_validation->set_rules("title", "Title", "required|trim|is_unique[product.title]");
$this->form_validation->set_rules("description", "Description", "required|trim");
$this->form_validation->set_rules("sale_price", "Price", "required|trim");
$this->form_validation->set_message(
array(
"required" => "<b>{field}</b> is not null.",
'is_unique' => 'A %s content has already been added in thistitle.!'
)
);
$validate = $this->form_validation->run();
if($validate){
$insert = $this->db->insert('product', $data);
// alert
if($insert){
$alert = array(
"title" => "Success Sir",
"text" => "Content successfully added",
"type" => "success"
);
}else {
$alert = array(
"title" => "Error Sir",
"text" => "Content failed to load content,
"type" => "danger"
);
}
}
JSON, AJAX, jQuery:
function ajax_set_full(type, title, noty, form_id, id) {
// ajax func
ajax_load(base_url + '' + user_type + '/' + module + '/' + type + '/' + id, 'list', 'form');
}
function form_submit(form_id, noty, e) {
var alerta = $('#form'); // alert div for show alert message
var form = $('#' + form_id);
var can = '';
if (!extra) {
var extra = '';
}
form.find('.summernotes').each(function () {
var now = $(this);
now.closest('div').find('.val').val(now.summernote('code'));
});
//var form = $(this);
var formdata = false;
if (window.FormData) {
formdata = new FormData(form[0]);
}
var a = 0;
var take = '';
form.find(".required").each(function () {
var txt = '*' + req;
a++;
if (a == 1) {
take = 'scroll';
}
var here = $(this);
if (here.val() == '') {
if (!here.is('select')) {
here.css({borderColor: 'red'});
if (here.attr('type') == 'number') {
txt = '*' + mbn;
}
if (here.closest('div').find('.require_alert').length) {
} else {
here.closest('div').append(''
+ ' <span id="' + take + '" class="label label-danger require_alert" >'
+ ' ' + txt
+ ' </span>'
);
}
} else if (here.is('select')) {
here.closest('div').find('.chosen-single').css({borderColor: 'red'});
if (here.closest('div').find('.require_alert').length) {
} else {
here.closest('div').append(''
+ ' <span id="' + take + '" class="label label-danger require_alert" >'
+ ' *Required'
+ ' </span>'
);
}
}
var topp = 100;
if (form_id == 'product_add' || form_id == 'product_edit') {
} else {
$('html, body').animate({
scrollTop: $("#scroll").offset().top - topp
}, 500);
}
can = 'no';
}
if (here.attr('type') == 'email') {
if (!isValidEmailAddress(here.val())) {
here.css({borderColor: 'red'});
if (here.closest('div').find('.require_alert').length) {
} else {
here.closest('div').append(''
+ ' <span id="' + take + '" class="require_alert" >'
+ ' *' + mbe
+ ' </span>'
);
}
can = 'no';
}
}
take = '';
});
if (can !== 'no') {
if (form_id !== 'vendor_pay') {
$.ajax({
url: form.attr('action'), // form action url
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: formdata ? formdata : form.serialize(), // serialize form data
cache: false,
contentType: false,
processData: false,
beforeSend: function () {
console.log(formdata);
var buttonp = $('.enterer');
buttonp.addClass('disabled');
buttonp.html(working);
},
success: function () {
ajax_load(base_url + '' + user_type + '/' + module + '/' + list_cont_func + '/' + extra, 'list', 'first');
if (form_id == 'vendor_approval') {
noty = enb_ven;
}
iziToast.show({
color: 'dark',
icon: 'fa fa-info',
title: 'Bilgi',
message: 'İşlem Başarılı!',
position: 'topCenter', // bottomRight, bottomLeft, topRight, topLeft, topCenter, bottomCenter
progressBarColor: 'rgb(0, 255, 184)',
/*onOpening: function(){
setTimeout(function(){
window.location.reload(1);
}, 5000);
console.log('Page Refresh!');
},
onClosing: function(){
// console.log('goodbye');
}*/
});
$('.bootbox-close-button').click();
('form_submit_success');
other_forms();
},
error: function (e) {
console.log(e)
}
});
} else {
//form.html('fff');
form.submit();
//alert('ff');
return false;
}
} else {
if (form_id == 'product_add' || form_id == 'product_edit') {
var ih = $('.require_alert').last().closest('.tab-pane').attr('aria-labelledby');
$("[id=" + ih +"]").click();
}
$('body').scrollTo('#scroll');
return false;
}
}
The error message always returns positive.
after run the validation, you need specify the array to be validated
public function save(){
$data = array();
$data['title'] = $this->input->post('title');
$data['description'] = $this->input->post('description');
$data['sale_price'] = $this->input->post('sale_price');
$data['purchase_price'] = $this->input->post('purchase_price');
$data['add_timestamp'] = time();
$this->form_validation->set_rules("title", "Title", "required|trim|is_unique[product.title]");
$this->form_validation->set_rules("description", "Description", "required|trim");
$this->form_validation->set_rules("sale_price", "Price", "required|trim");
$this->form_validation->set_message(
array(
"required" => "<b>{field}</b> is not null.",
'is_unique' => 'A %s content has already been added in thistitle.!'
)
);
$this->form_validation->set_data($data);
$validate = $this->form_validation->run();
You have to call the set_data() method before defining any validation rules.
Ref: https://codeigniter.com/userguide3/libraries/form_validation.html#validating-an-array-other-than-post

jqGrid - Keep checkbox selected on grid reload when editing form

I have a form that utilizes jqGrid to display personalized info for the user to select from. Everything works fine however on the "Review" page there is an option to edit the form. When you click edit and go back into the form selections all values selected are retained except for the jqGrid portion of the form that uses the checkbox values. How can I have this value retained so the user doesn't have to make the selection again?
var myGrid;
var blnListsFound = true;
var blnGridLoading = false;
function fnInitialize() {
// Initialize the screen
fnLoadForm();
$('#no_transactions').hide();
// alert("fnInitialize(): JS loaded fine, no errors");
}
function fnACHSwapGetGrid() {
blnListsFound = true;
// make sure we have a from account
if ($('#selFromAccount').val() == '0') {
return;
}
$('#imgWaitselFromAccount').show(); // show loading icon
var urlString = '';
var urlParams = new Array();
// urlParams['rc'] = escape($('#RC').val());
urlParams['RC'] = escape($('#txtMenuRC').val());
urlParams['acctNBR'] = escape($('#selFromAccount').val());
// get application type from aryAccount
for (act in aryAccount) {
if (aryAccount[act]['Number'] == urlParams['acctNBR']) {
urlParams['Appl'] = aryAccount[act]['Application'];
break;
}
}
$.jgrid.gridUnload("#list");
myGrid = $("#list").jqGrid({
url: baseURL + '/scripts/get_user_list.php' + urlString,
datatype: "json",
mtype: 'POST',
width: 660,
height: '100%',
pager: '#pager',
rowNum: 10,
rowList: [20, 30, 40, 50, 60],
sortname: 'id',
sortorder: "asc",
viewrecords: true,
multiselect: true,
repeatitems: false,
imgpath: '/scripts/jquery-ui/images',
colNames: ['id', 'Building', 'Company ID', 'Description', 'Individual Name', 'SECCode'],
colModel: [
{name: 'id', index: 'id', jsonmap: 'id', hidden: true, width: 20},
{name: 'Building', index: 'Building', jsonmap: 'Building', hidden: true, width: 20},
{name: 'CompanyId', index: 'CompanyId', jsonmap: 'CompanyId', width: 110},
{name: 'Description', index: 'Description', jsonmap: 'Description', sortable: true, width: 300},
{name: 'IndName', index: 'IndName', jsonmap: 'IndName', width: 200},
{name: 'UsrNum', hidden: true, index: 'UsrNum', jsonmap: 'UsrNum'}
],
jsonReader:
{
repeatitems: false,
root: 'rows',
id: '0',
cell: '',
subgrid:
{
root: 'rows',
id: '0',
cell: '',
repeatitems: false
}
},
// subgrid support
subGrid: true,
subGridUrl: baseURL + '/scripts/get_user_list.php' + urlString,
subGridModel: [{
name: ['Date', 'ID'],
params: ['CompanyId'],
align: ['center', 'right'],
width: [150, 80]}
],
ondblClickRow: function (id)
{
$('#recId').val(id);
},
beforeRequest: function ()
{
blnGridLoading = true;
// console.log("beforeRequest(); setting blnGridLoading=true");
fnValidateAccount(); // Check that user has data available
},
loadComplete: function ()
{
blnGridLoading = false;
// console.log("loadcomplete(); setting blnGridLoading=false");
for (swap in arySwap)
{
if (typeof arySwap[swap]['CompanyId'] != 'undefined')
{
$("#list").jqGrid('setSelection', arySwap[swap]['CompanyId']); // select companyId
}
}
fnValidateAccount(); // Check that user has data available
},
loadError: function (jqXHR, textStatus, errorThrown)
{
blnGridLoading = false;
blnListsFound = false; // no data found for this account
// console.log("loadError() setting blnGridLoading=false and blnListsFound=false");
fnValidateAccount(); // Check that user has data available
//alert('HTTP status code: ' + jqXHR.status + '\n' +
// 'textStatus: ' + textStatus + '\n\n ' +
// 'errorThrown: ' + errorThrown);
//alert('HTTP message body (jqXHR.responseText): ' + '\n' + jqXHR.responseText);
}
})
.navGrid('#pager', {edit: false, add: false, del: false, search: false, refresh: true});
//$("#list").closest('.ui-jqgrid-bdiv').width($("#list").closest('.ui-jqgrid-bdiv').width() + 10);
$('#imgWaitselFromAccount').hide(); // hide loading icon
fnfldDisable("selToAccount", false);
}
function fnLoadForm() {
for (swap in arySwap) {
if ($('#selFromAccount').val() != 0) {
break; // populate just once
}
if (typeof arySwap[swap]['FromAccount'] != 'undefined' // have swap data
&& arySwap[swap]['FromAccount'] != '' // and its not blank
)
{
$('#selFromAccount').val(arySwap[swap]['FromAccount']);
$('#selFromAccount').change(); // trigger change calls
$('#selToAccount').val(arySwap[swap]['ToAccount']);
$('#selToAccount').change(); // trigger change calls
}
}
}
function fnGetAccountTitle(objAccount, fldTitle) {
if (typeof objAccount != 'object') {
return false;
}
if (typeof fldTitle != 'string') {
return false;
}
if ($('#' + fldTitle).length) {
$('#' + fldTitle).val('');
var curAccount = fnGetSelected(objAccount);
for (act in aryAccount) {
if (aryAccount[act]['Number'] == curAccount) {
var Application = fldTitle.replace('Title', 'Application');
$('#' + fldTitle).val(aryAccount[act]['Title']);
$('#' + Application).val(aryAccount[act]['Application']);
return;
}
}
}
}
function fnValidateAccount() {
var blndoSubmit = true;
// console.log("fnValidateAccount() called.");
$("#list").removeClass("errmark"); // reset error display
if (blnGridLoading) {
$("#no_data").hide();
reValidateTimer = setTimeout("fnValidateAccount()", 2000);
// console.log("Grid loading, retrying validation in 5 seconds");
blndoSubmit = false;
}
else {
var numRows = $("#list").jqGrid('getGridParam', 'records'); // rows available
var selRows = $("#list").jqGrid('getGridParam', 'selarrrow'); // rows selected
if (numRows < 1 || blnListsFound == false) {
$("#no_transactions").show();
$("#divTransactions").hide();
fnDoInvalidData('list', 'No data was found for this account.', true);
// $("#list").jqGrid('GridUnload');
blndoSubmit = false;
}
}
return blndoSubmit;
}
function fnValidate() {
// Validate data that has been entered by the user.
var blndoSubmit = true; // Should we submit the form?
// console.log("fnValidate() " + new Date() );
// console.log("fnValidate() called.");
fnResetInvalidFields('frmData'); // Reset the fields marked as errored.
if (!$('#chkSaveRecord').is(':checked')) {
return true;
}
$('#CompanyIds').val("");
if (!$('#chkEmailNone').is(':checked')) {
if (!fnCheckEmail($('#txtEmail').val())) {
fnDoInvalidData('txtEmail', 'Email Address is not valid.', true);
blndoSubmit = false;
}
}
var numRows = $("#list").jqGrid('getGridParam', 'records');
var selRows = $("#list").jqGrid('getGridParam', 'selarrrow');
// console.log(numRows + ' records loaded, ' + selRows.length + ' selected');
accountValidated = fnValidateAccount();
if (!accountValidated) {
// function shows no_transactions container for us
fnDoInvalidData('list', 'No data found for this account.', true);
// console.log("validateAccount gave failure.");
blndoSubmit = false;
}
var tmpselAccount = fnGetSelected('selFromAccount');
if ((tmpselAccount == '') || (tmpselAccount == '0')) {
fnDoInvalidData('selFromAccount', 'Selection required.', true);
blndoSubmit = false;
}
var tmpselAccount = fnGetSelected('selToAccount');
if ((tmpselAccount == '') || (tmpselAccount == '0')) { // swap to
fnDoInvalidData('selToAccount', 'Selection is required.', true);
blndoSubmit = false;
}
if (fnGetSelected('selFromAccount') == fnGetSelected('selToAccount')) {
fnDoInvalidData('selToAccount', 'Selections must be different.', true);
blndoSubmit = false;
}
// if undefined or no rows or no available
if (!blnListsFound) {
fnDoInvalidData('list', 'No data was found for this account.', true);
blndoSubmit = false;
}
if (!accountValidated) {
fnDoInvalidData('list', 'No data was found for this account.', true);
blndoSubmit = false;
}
if (!blnGridLoading) {
if (numRows && (typeof (selRows) === "undefined" || !selRows || !selRows.length)) {
fnDoInvalidData('list', 'At least one item must be selected.', true);
fnDoInvalidData('selFromAccount', 'At least one item must be selected.', true);
blndoSubmit = false;
}
if (numRows && (typeof (selRows) !== "undefined" && selRows && selRows.length)) {
// collect selected companyid rows from jqGrid
var aryCompanyIds = [];
for (var i = 0; i < selRows.length; i++) {
aryCompanyIds.push(
$("#list").jqGrid('getCell', selRows[i], 'Routing')
+ '=' + $("#list").jqGrid('getCell', selRows[i], 'CompanyId')
+ '=' + $("#list").jqGrid('getCell', selRows[i], 'Description')
+ '=' + $("#list").jqGrid('getCell', selRows[i], 'IndName')
);
}
// set values in hidden field
$('#CompanyIds').val(aryCompanyIds.join("||"));
}
}
else {
// grid still loading
blndoSubmit = false;
}
if (blndoSubmit === false) {
fnACHSwapGetGrid();
}
return blndoSubmit;
}

Highcharts multiple series json from php

Hi guys i need help with Highcharts library, i have this array coming from php,
[{"name":"25% en cambio de aceite 76 lubricants","data":[["2015-09-07",1],["2015-09-23",2],["2015-09-24",3],["2015-09-30",3]]},{"name":"10% Descuento en filtro de aceite","data":[["2015-09-07",1],["2015-09-23",2],["2015-09-24",3],["2015-09-30",3],["2015-10-03",3],["2015-10-05",1],["2015-10-09",1],["2015-10-10",1]]}]
I need to show this as line chart dynamically, but have been unable to do it, i believe the error comes from the quotes in dates, needs to be in format [Date.UTC(2015, 2, 6), 3]
This is my php function that returns the json data
public function actionTransactionsRedeemed() {
// Transacciones Totales redimidas por merchant
$sql = "SELECT DISTINCT `transaction`.idPromotion, promotion.`name` FROM `transaction` INNER JOIN promotion ON `transaction`.idPromotion = promotion.idPromotion WHERE `transaction`.idMerchant = 2 AND `transaction`.idPromotion IS NOT NULL";
$idPromotion = Yii::app()->db->createCommand($sql)->queryAll();
$idPromotions = array();
$tempArray = array();
$result = array();
$i = 1;
$rs = array();
foreach($idPromotion as $i){
//process each item here
$id = $i["idPromotion"];
$tempArray['name'] = $i["name"];
$sql = "SELECT count(*) AS count, DATE(`transaction`.date) AS `date` FROM `transaction` WHERE `transaction`.idMerchant = 2 AND `transaction`.idPromotion = $id GROUP BY DATE(`transaction`.date)";
$transactionsRedeemed = Yii::app()->db->createCommand($sql)->queryAll();
foreach($transactionsRedeemed as $item2){
$rs[0] = $item2['date'];
$rs[1] = $item2['count'];
$tempArray['data'][] = $rs;
$rs = array();
}
$i++;
array_push($result, $tempArray);
}
//$result = json_encode($result, JSON_NUMERIC_CHECK);
//echo json_decode($result);
print json_encode($result, JSON_NUMERIC_CHECK);
}
And this is the Jquery that builds the chart
$(document).ready(function() {
var options = {
chart: {
type: 'spline',
renderTo: 'chart-merchant-day',
defaultSeriesType: 'spline',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'Total de promociones redimidas',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats: { // don't display the dummy year
month: '%e. %b',
year: '%b'
},
labels: {
align: 'center',
x: -3,
y: 20,
formatter: function() {
return Highcharts.dateFormat('%l%p', this.value);
}
}
},
yAxis: {
title: {
text: 'Transacciones'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return Highcharts.dateFormat('%l%p', this.x-(24000*3600)) +'-'+ Highcharts.dateFormat('%l%p', this.x) +': <b>'+ this.y + '</b>';
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: [{
name: 'Count'
}],
credits: false
}
// Load data asynchronously using jQuery. On success, add the data
// to the options and initiate the chart.
jQuery.get('?r=/transactions/transactionsRedeemed', null, function(tsv) {
var lines = [];
traffic = [];
var data = $.parseJSON(tsv);
var x = 0;
//console.log(tsv);
$.each(data, function(i, item) {
//alert(item);
//console.log(item);
$.each(item, function(y, item2) {
if(y == "data"){
//console.log(item2);
try {
tsv = item2;
// split the data return into lines and parse them
tsv = tsv.split(/\n/g);
jQuery.each(tsv, function(i, line) {
line = line.split(/\t/);
options.series[x].data.push([Date.parse(line[0]),line[1]]);
/*date = Date.parse(line[0] +' UTC');
traffic.push([
date,
parseInt(line[1].replace(',', ''), 10)
]);*/
});
} catch (e) { }
options.series[x].data = traffic;
} else if(y == "name"){
options.series[x].name = item2;
}
});
x++;
});
chart = new Highcharts.Chart(options);
//console.log(tsv.replace(/\"/g, ""));
//tsv = tsv.replace(/\"/g, "");
});
});
Any help will be greatly appreciated, im so exhausted at this point.
The function is actually simpler,
jQuery.get('?r=/transactions/transactionsRedeemed', null, function(tsv) {
var data = $.parseJSON(tsv);
$.each(data, function (i, item) {
options.series.push({
name: item['name'],
data: []
});
$.each(item['data'], function (j, dataitem) {
var dataitemvalue = null;
try {
dataitemvalue = [Date.parse(dataitem[0]), dataitem[1]];
} catch (e) {}
options.series[i].data.push(dataitemvalue);
});
});
chart = new Highcharts.Chart(options);
});
JSFiddle demo

dojo.xhrGet Not Sending any Data

I want to take dojo Get data from ajax to php
Dojo passing parameter i couldn't take it in php class.
passing the cpa is not pass to php file..
This is my code :
globalHandlers: {
doVsatEvents: function(vsatId, network, cpa) {
// retrieve the events via xml
dojo.xhrGet ({
url: "includes/vsat_events.php?",
handleAs: "xml",
preventCache: true,
content: {
network: network,
cpa: cpa
},
load: function(response, args) {
var temp = response.getElementsByTagName("event");
var eventsItems =[];
alert (temp.length);
for (var i = 0; i < temp.length; i++) {
var event = [];
event = [];
event['id'] = temp[i].getAttribute(['id']);
event['nms'] = temp[i].getAttribute(['nms']);
event['status'] = temp[i].getAttribute(['status']);
event['date'] = temp[i].getAttribute(["date"]);
event['time'] = temp[i].getAttribute(["time"]);
event['description'] = temp[i].getAttribute(["description"]);
alert (events['description']);
eventsItems.push(event);
}
var eventsGridData = {
identifier: 'id',
items: eventsItems
};
// build a floating pane
var fPane = SM.util.skymapFloatingPane("Events", "eventsFPID_" + SM.getNextId());
var eventsStore = new dojo.data.ItemFileReadStore({
data: eventsGridData,
clearOnClose: true
});
// set the layout structure: 720px
// scrollbar is 14px wide
var eventsLayout = [{
field: 'id',
name: 'ID',
width: '60px'
},{
field: 'nms',
name: 'NMS',
width: '55px'
},{
field: 'status',
name: 'Severity',
width: '60px'
},{
field: 'date',
name: 'Date',
width: '100px'
},{
field: 'time',
name: 'Time',
width: '90px'
},{
field: 'description',
name: 'Description',
width: '400px'
}];
// create a new grid:
var eventsGrid = new dojox.grid.DataGrid({
query: {
id: '*'
},
store: eventsStore,
clientSort: true,
rowSelector: '20px',
structure: eventsLayout
}, document.createElement('div'));
// append the new grid to the div "gridContainer4":
fPane.set('content', eventsGrid);
//document.body.appendChild(fPane.domNode);
fPane.startup();
fPane.show();
}
});
},
This is my PHP code :
<?php
chdir('../../../');
include_once("./include/auth.php");
// Start XML file, create parent node
$doc = new DOMDocument;
$node = $doc->createElement("events");
$parnode = $doc->appendChild($node);
$query = "SELECT * FROM `skymap_1_nms_events`";
$query .= " WHERE `cpa` = ".$_GET['cpa'];
$query .= " ORDER BY `id` DESC";
//print $query;
$result = mysql_query ($query);
header("Content-type: text/xml");
while($row = mysql_fetch_assoc($result)){
$status = $row['severity'];
if ($status == 3){
$status = "normal";
} elseif($status == 1) {
$status = "disabled";
} elseif($status == 2) {
$status = "unmanaged";
} elseif($status == 4) {
$status = "warning";
} elseif($status == 5) {
$status = "minor";
} elseif($status == 6) {
$status = "major";
} elseif($status == 7) {
$status = "critical";
} else {
$status = "unknown";
}
$childnode = $doc->createElement("event");
$newnode = $parnode->appendChild($childnode);
$newnode->setAttribute("id", $row['id']);
$newnode->setAttribute("nms", $row['reporting_nms']);
$newnode->setAttribute("status", $status);
$newnode->setAttribute("date", $row['date']);
$newnode->setAttribute("time", $row['time']);
$newnode->setAttribute("description", $row['description']);
}
$xmlfile = $doc->saveXML();
echo $xmlfile;
?>
any help?

Error: GET http://mywebsite.com/tmp/highchart_oqoCdS 403 (Forbidden)

The server seems pretty unhappy trying to work with the jQuery min file. The error that is being reported is:
GET http://mywebsite.com/tmp/highchart_C6MyqK 403 (Forbidden)
jquery.min.js:2
The highchart_C6MyqK is a json file that is created with a random name from the code below. My eventual goal is to create this Highstock chart:
http://www.highcharts.com/stock/demo/compare
Though when loading the page, it stays blank with the forbidden error. I have tried this code on two different server hosts with the same error.
Here is my code. The first half is getting the data, the second half is creating the graph.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js">
</script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script src="http://code.highcharts.com/stock/highstock.js"></script>
<script src="http://code.highcharts.com/stock/modules/exporting.js"></script>
<?php
//Find all .csv files
$files = glob('*.csv');
$dates = array();
for($i=0;$i<count($files);$i++){
$str = substr($files[$i],-14, -4);
$dates[] = $str;
}
sort($dates);
//Get data from csv files
$tmpFile = tempnam('tmp/','highchart_');
$out = fopen($tmpFile, "w");
fputs($out, '[');
for($i=0;$i<count($files);$i++){
if (($handle = fopen($files[$i], "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ',')) !== FALSE) {
$timestamp = strtotime($data[0].' '.$data[1]);
fputs($out, '['.(int)$timestamp.','.(float)$data[2].','.
(float)$data[3].','.(float)$data[4].','.(float)$data[5].','.
(float)$data[12].','.(float)$data[13].']');
}
fclose($handle);
}
}
fputs($out, ']');
fclose($out);
?>
<script type="text/javascript">
$(function() {
var seriesOptions = [],
yAxisOptions = [],
seriesCounter = 0,
names = ['CBS min', 'CBS max', 'CBS avg. peak min', 'CBS avg. peak max', 'LKFS', 'LRA' ],
colors = Highcharts.getOptions().colors;
$.each(names, function(i, name) {
$.getJSON('<? echo $tmpFile ?>', function(data) {
seriesOptions[i] = {
name: name,
data: data
};
seriesCounter++;
if (seriesCounter == names.length) {
createChart();
}
});
});
// create the chart when all data is loaded
function createChart() {
$('#container').highcharts('StockChart', {
chart: {
},
rangeSelector: {
selected: 4
},
yAxis: {
labels: {
formatter: function() {
return (this.value > 0 ? '+' : '') + this.value + '%';
}
},
plotLines: [{
value: 0,
width: 2,
color: 'silver'
}]
},
plotOptions: {
series: {
compare: 'percent'
}
},
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b> ({point.change}%)<br/>',
valueDecimals: 2
},
series: seriesOptions
});
}
});
</script>
<div id="container" style="height: 500px; min-width: 600px"></div>
Thanks in advance for your insight!
The problem is probably related to the permissions of the JSON file you created. Check if it has read permissions (for everyone, not only the file's owner).
If not (which is probably the case), put this at the end of your PHP function creating the file, under fclose($out):
chmod($tmpFile, 0644); # Read/write for file owner, read for everyone else
It needs to be readable by everyone since JavaScript is executed client-side and not server-side.

Categories