Line chart from json response in html / javascript / php - javascript

I'm trying to create a single line chart of a json response(sql) in html/javascript. What im trying to create is a chart with only one line of the tag_name, in the case below: "phone 4". This line should represent all values and datetimes of all json strings.
JSON response:
[{"tag_name":"phone 4","value":"4","datetime":"2017-10-03 14:20:09"},
{"tag_name":"phone 4","value":"4","datetime":"2017-10-03 14:19:49"},
{"tag_name":"phone 4","value":"4","datetime":"2017-10-03 14:19:29"},
{"tag_name":"phone 4","value":"4","datetime":"2017-10-03 14:19:09"},
{"tag_name":"phone 4","value":"4","datetime":"2017-10-03 14:18:49"},
{"tag_name":"phone 4","value":"4","datetime":"2017-10-03 14:18:29"},
{"tag_name":"phone 4","value":"4","datetime":"2017-10-03 14:18:09"},
{"tag_name":"phone 4","value":"4","datetime":"2017-10-03 14:17:49"},
{"tag_name":"phone 4","value":"4","datetime":"2017-10-03 14:17:29"},
{"tag_name":"phone 4","value":"4","datetime":"2017-10-03 14:17:09"}]
What i've reached so far(not much):
<script type="text/javascript">
google.charts.load('current', {'packages': ['line']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('number', 'Datetime');
data.addColumn('number', 'Values');
var options = {
chart: {
title: 'Values',
},
width: 900,
height: 500
};
var chart = new google.charts.Line(document.getElementById('chart_div'));
chart.draw(data, google.charts.Line.convertOptions(options));
}
</script>
How my php code looks like:
require_once 'db_connection.php';
header('Content-type: application/json');
$data = array();
$Chart = "SELECT *
FROM (
SELECT *,
#rn := if( #tag_name = tag_name,
#rn + 1,
if(#tag_name := tag_name, 1, 1)
) as tag_count
FROM waardes
CROSS JOIN ( SELECT #rn := 0, #tag_name := '') as vars
ORDER BY tag_name
) as T
WHERE tag_count < 11 AND machine_id LIKE 3 AND tag_name LIKE 'phone 4'
ORDER BY datetime DESC";
$result = mysqli_query($connection, $Chart);
while ($row = mysqli_fetch_array($result)) {
if ($row["int_value"] == 0 && $row["real_value"] == 0.0 && $row["bool_value"] != "") {
array_push($data, array('tag_name' => $row['tag_name'], 'value' => $row['bool_value'], 'datetime' => $row['datetime']));
} elseif ($row["int_value"] == 0 && $row["real_value"] != 0 && $row["bool_value"] == "") {
array_push($data, array('tag_name' => $row['tag_name'], 'value' => $row['real_value'], 'datetime' => $row['datetime']));
} elseif ($row["int_value"] != 0 && $row["real_value"] == 0 && $row["bool_value"] == "") {
array_push($data, array('tag_name' => $row['tag_name'], 'value' => $row['int_value'], 'datetime' => $row['datetime']));
}
}
echo json_encode($data);

first, don't recommend mixing php and javascript in the same file
separate the html / javascript from the php
use ajax to get the data from php to javascript
for google charts, use the json format found here...
Format of the Constructor's JavaScript Literal data Parameter
this will allow you to create the google data table, directly from the json
getdata.php
require_once 'db_connection.php';
header('Content-type: application/json');
$data = array();
$Chart = "SELECT *
FROM (
SELECT *,
#rn := if( #tag_name = tag_name,
#rn + 1,
if(#tag_name := tag_name, 1, 1)
) as tag_count
FROM waardes
CROSS JOIN ( SELECT #rn := 0, #tag_name := '') as vars
ORDER BY tag_name
) as T
WHERE tag_count < 11 AND machine_id LIKE 3 AND tag_name LIKE 'phone 4'
ORDER BY datetime DESC";
$result = mysqli_query($connection, $Chart);
$data = array();
$data['cols'] = array(
array('label' => 'Date', 'type' => 'string'),
array('label' => 'phone 4', 'type' => 'number')
);
$data['rows'] = array();
while ($row = mysqli_fetch_array($result)) {
if ($row["int_value"] == 0 && $row["real_value"] == 0.0 && $row["bool_value"] != "") {
$row = array();
$row[] = array('v' => (string) $row['datetime']);
$row[] = array('v' => (float) $row['bool_value']);
$data['rows'][] = array('c' => $row);
} elseif ($row["int_value"] == 0 && $row["real_value"] != 0 && $row["bool_value"] == "") {
$row = array();
$row[] = array('v' => (string) $row['datetime']);
$row[] = array('v' => (float) $row['real_value']);
$data['rows'][] = array('c' => $row);
} elseif ($row["int_value"] != 0 && $row["real_value"] == 0 && $row["bool_value"] == "") {
$row = array();
$row[] = array('v' => (string) $row['datetime']);
$row[] = array('v' => (float) $row['int_value']);
$data['rows'][] = array('c' => $row);
}
}
$data['rows'] = $rows;
echo json_encode($data);
JavaScript
google.charts.load('current', {
packages: ['line']
}).then(function () {
$.ajax({
url: 'getdata.php',
dataType: 'json'
}).done(function (jsonData) {
var data = new google.visualization.DataTable(jsonData);
var options = {
chart: {
title: 'Values'
},
width: 900,
height: 500
};
var chart = new google.charts.Line(document.getElementById('chart_div'));
chart.draw(data, google.charts.Line.convertOptions(options));
}).fail(function (jq, text, errMsg) {
console.log(text + ': ' + errMsg);
});
});
this will give you a better structure to handle multiple charts / data tables
now, if you wanted to use a real date in the chart, instead of a string (as in the above php)
it would allow you to use chart options such as format, for the x-axis
you can pass the date value as a string, in the following format found here...
Dates and Times Using the Date String Representation
"Date(Year, Month, Day, Hours, Minutes, Seconds, Milliseconds)"
to do this, change the column type to date...
array('label' => 'Date', 'type' => 'date'),
then when loading the data, using the following to format as above...
$rowDate = "Date(".date_format($row['datetime'], 'Y').", ".((int) date_format($row['datetime'], 'm') - 1).", ".date_format($row['datetime'], 'd').", ".date_format($row['datetime'], 'H').", ".date_format($row['datetime'], 'i').", ".date_format($row['datetime'], 's').")";
$row = array();
$row[] = array('v' => (string) $rowDate);
$row[] = array('v' => (float) $row['bool_value']);
$data['rows'][] = array('c' => $row);
note: month numbers are zero-based in javascript...

Related

Send 2 variables through url

I send 2 variables by url:
var http = false;
http = new XMLHttpRequest();
function carrega(){
var nome = document.getElementById('CodigoUtente').value;
var nomes = document.getElementById('Nome').value;
var url_="conexao4?CodigoUtente="+nome+"&Nome="+nomes;
http.open("GET",url_,true);
http.onreadystatechange=function(){
if(http.readyState==4){
var retorno = JSON.parse(http.responseText);
document.getElementById('CodigoUtente').value = retorno.CodigoUtente;
document.getElementById('Nome').value = retorno.Nome;
document.getElementById('DataNasc').value = retorno.DataNasc;
document.getElementById('Sexo').value = retorno.Sexo;
document.getElementById('Estadocivil').value = retorno.Estadocivil;
document.getElementById('Nacionalidade').value = retorno.Nacionalidade;
document.getElementById('Responsavel').value = retorno.Responsavel;
document.getElementById('Parentesco').value = retorno.Parentesco;
document.getElementById('Contato').value = retorno.Contato;
}
}
http.send(null);
}
in the connection page4 I have the php that receives the variables:
$CodigoUtente = $_GET['CodigoUtente'];
$Nome = $_GET['Nome'];
if((isset($CodigoUtente)) && (isset($Nome))){
$query= "SELECT CodigoUtente, Nome, DataNasc, Sexo, Estadocivil, Nacionalidade, Responsavel, Parentesco, Contato FROM centrodb.PsicUtentes WHERE (CodigoUtente = '$CodigoUtente') OR (Nome LIKE '%$Nome%')";
$resultados = $conn->query($query);
$json = array();
while ($rowResultados = $resultados->fetch_assoc()) {
$dados = array(
'CodigoUtente' => $rowResultados['CodigoUtente'],
'Nome' => $rowResultados['Nome'],
'DataNasc' => $rowResultados['DataNasc'],
'Sexo' => $rowResultados['Sexo'],
'Estadocivil' => $rowResultados['Estadocivil'],
'Nacionalidade' => $rowResultados['Nacionalidade'],
'Responsavel' => $rowResultados['Responsavel'],
'Parentesco' => $rowResultados['Parentesco'],
'Contato' => $rowResultados['Contato']
);
$json = $dados;
}
echo json_encode($json);
}
The problem is that they only work if you fill in the two inputs and intended that they return the data from the database only when filling one of them.
Curious_Mind was saying this way?
$where_caluse = array();
if(isset($_GET['CodigoUtente'])){
$where_caluse[] = "CodigoUtente = '".$_GET['CodigoUtente']."'";
}
if(isset($_GET['Nome'])){
$where_caluse[] = "Nome = '".$_GET['Nome']."'";
}
$where = array_filter($where_caluse);
$query = "SELECT CodigoUtente, Nome, DataNasc, Sexo, Estadocivil, Nacionalidade, Responsavel, Parentesco, Contato FROM centrodb.PsicUtentes";
$resultados = $conn->query($query);
if(!empty($where)){
$final_where = count($where) > 1 ? implode(' OR ', $where) : end($where);
$query = "$query WHERE ". $final_where;
$json = array();
while ($rowResultados = $resultados->fetch_assoc()) {
$dados = array(
'CodigoUtente' => $rowResultados['CodigoUtente'],
'Nome' => $rowResultados['Nome'],
'DataNasc' => $rowResultados['DataNasc'],
'Sexo' => $rowResultados['Sexo'],
'Estadocivil' => $rowResultados['Estadocivil'],
'Nacionalidade' => $rowResultados['Nacionalidade'],
'Responsavel' => $rowResultados['Responsavel'],
'Parentesco' => $rowResultados['Parentesco'],
'Contato' => $rowResultados['Contato']
);
$json = $dados;
}
echo json_encode($json);
}
I tried to apply the form it said, but it is not working, it gives 500 error when I send the values ​​of the variables.
Can you help fix the problem? I have a form to be populated with these values
$where = " where ";
$CodigoUtente = 'a';
$Nome = '';
if($CodigoUtente != '' && $Nome != '')
{
$where .= "CodigoUtente = '$CodigoUtente' OR Nome = '$Nome';";
}else if ($CodigoUtente != ''){
$where .= "CodigoUtente = '$CodigoUtente';";
}else{
$where .= " Nome = '$Nome';";
}
$query = "SELECT CodigoUtente, Nome, DataNasc, Sexo, Estadocivil, Nacionalidade, Responsavel, Parentesco, Contato FROM centrodb.PsicUtentes".$where;
echo $query;
You can try like this way before making you sql query. This will help you to handle WHERE with OR condition, without OR condition and without any condition at all.
$where = array();
$_GET['CodigoUtente'] = 'Sany';
$_GET['Nome'] = 'Bruno';
if(isset($_GET['CodigoUtente'])){
$where[] = "CodigoUtente = '".$_GET['CodigoUtente']."'";
}
if(isset($_GET['Nome'])){
$where[] = "Nome = '".$_GET['Nome']."'";
}
$sql = "SELECT CodigoUtente, Nome, DataNasc, Sexo, Estadocivil, Nacionalidade, Responsavel, Parentesco, Contato FROM centrodb.PsicUtentes";
if(!empty($where)){
$final_where = count($where) > 1 ? implode(' OR ', $where) : end($where);
$sql = "$sql WHERE ". $final_where;
}
echo $sql;
DEMO: https://3v4l.org/phZGW

How to generate alert when entered qty is more than available stock

I have created one IMS System. In that my stock is going in negative and I have to stop it so my main intention is to generate the alert when the entered product is more than available stock(Ex. if a user is entering 12 qty and in stock only available is 10 qty than alert message should generate like entered quantity is more than available stock so you can't generate order).Below is my code
public function create()
{
$user_id = $this->session->userdata('id');
$query = $this->db->query("SELECT bill_no FROM orders ORDER BY id DESC LIMIT 1");
$result = $query->row()->bill_no;
$result++;
//echo $result;
//end();
//$curYear = date('Y');
$invoice_no = $result;
//$invoice['invoice_no'] = $invoice_no;
$data = array(
'po_no' => $this->input->post('po_no'),
'po_date' => $this->input->post('po_date'),
'challan_no' => $this->input->post('challan_no'),
'challan_date' => $this->input->post('challan_date'),
'bill_no' => $invoice_no,
'bill_date' => $this->input->post('bill_date'),
'terms' => $this->input->post('terms'),
'dispatch' => $this->input->post('dispatch'),
'party_id' => $this->input->post('id'),
'name' => $this->input->post('name_value'),
'address' => $this->input->post('address_value'),
'gstin' => $this->input->post('gstin_value'),
'mobile' => $this->input->post('mobile_value'),
'date_time' => strtotime(date('Y-m-d h:i:s a')),
'qty' => $this->input->post('qty_value'),
'gross_amount' => $this->input->post('gross_amount_value'),
'central_amount' => $this->input->post('central_amount_value'),
'net_amount' => $this->input->post('net_amount_value'),
'round_amount' =>$this->input->post('round_amount_value'),
'round_amount_words' => $this->input->post('round_amount_words'),
'paid_status' => 2,
'user_id' => $user_id
);
$insert = $this->db->insert('orders', $data);
$order_id = $this->db->insert_id();
$this->load->model('model_products');
$count_product = count($this->input->post('product'));
for($x = 0; $x < $count_product; $x++) {
$items = array(
'order_id' => $order_id,
'product_id' => $this->input->post('product')[$x],
'hsn' => $this->input->post('hsn_value')[$x],
'rate' => $this->input->post('rate')[$x],
'qty' => $this->input->post('qty')[$x],
'unit' => $this->input->post('unit_value')[$x],
'amount' => $this->input->post('amount_value')[$x],
'gst' => $this->input->post('gst_value')[$x],
'gst_amount' => $this->input->post('gst_amount_value')[$x],
'last_amount' => $this->input->post('last_amount_value')[$x],
);
$this->db->insert('orders_item', $items);
// now decrease the stock from the product
$product_data = $this->model_products->getProductData($this->input->post('product')[$x]);
$qty = (int) $product_data['qty'] - (int) $this->input->post('qty')[$x];
$update_product = array('qty' => $qty);
$this->model_products->update($update_product, $this->input->post('product')[$x]);
}
return ($order_id) ? $order_id : false;
}
In your product_model, you could add a method to return the product count.
class Products_model extends CI_Model
{
...
/**
* Returns product quantity in db
* #param string $product_id
* #return integer
*/
public function productQty($product_id)
{
$qty = $this->db->query("SELECT `qty` FROM `products`"
. " WHERE product_id = `$product_id` ...")->result_array();
return (int) $qty[0]['qty'];
}
...
}
Then in your create() above, you can just check if ordered quantity is less than existing quantity.
...
for($x = 0; $x < $count_product; $x++) {
$qtyOrdered = (int) $this->input->post('qty')[$x];
if ($this->model_products->productQuantity(
$this->input->post('product')[$x]
) < $qtyOrdered) {
// Quantity is less. Do something like alert concerned people
} else {
// Continue
}
}
...

how i must using if for this angularjs and php code

I want to make one if for doing if array result was success alart somethings in
this code: if( data.status == 'success'){ is not working!!
it was with one = but result of one = is alwase 200 , I want to check status array if was success alert ...
I testthis code: data.data.statusin other place with just one array and this code work but when i use data.data.status in bottom codes its not working !!
angularjs function code :
$scope.book = function(){
if( $scope.cabs[$scope.active_cab].intialkm >= $scope.trip_distance) {
$scope.trip_rate = $scope.cabs[$scope.active_cab].intailrate ;
}else{
var init_rate = $scope.cabs[$scope.active_cab].intailrate ;
var std_rate = ( $scope.trip_distance - $scope.cabs[$scope.active_cab].intialkm ) * $scope.cabs[$scope.active_cab].standardrate ;
$scope.trip_rate = round_num( parseFloat(init_rate) + parseFloat(std_rate) );
}
$rootScope.user_data = JSON.parse( localStorage.getItem('user_data') );
var link = 'book_cab';
var post_data = {
'user_name' : $rootScope.user_data.User_name,
'token' : $rootScope.user_data.token,
'transfertype' : "Point to Point Transfer" ,
'book_date' : $scope.book_date ,
'pickup_area' : $scope.start_box.location,
'drop_area' : $scope.end_box.location,
'taxi_type' : $scope.selected_cab.cartype,
'km' : $scope.trip_distance,
'amount' : $scope.trip_rate
}
WebService.show_loading();
var promise = WebService.send_data( link,post_data);
promise.then(function(data){
$ionicLoading.hide();
if( data.status == 'success'){
alertPopup = $ionicPopup.alert({
title: '<p class="text-center color-yellow">'+$filter('langTranslate')("SUCCESS",$rootScope.appConvertedLang['SUCCESS'])+'</p>',
template: '<p class="text-center color-gery">'+$scope.trip_distance+' KM</p>'+
'<p class="text-center color-gery"> ₹ '+$scope.trip_rate+'</p>'
});
animateMyPop();
}else{
window.alert(response.data);
window.alert(response.status);
}
});
}
php webservice :
public function book_cab(){
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$request->uneaque_id = 'CMC'.strtotime(date('m/d/Y H:i:s'));
$myDate = new DateTime();
$myDate->setTimestamp( strtotime( $request->book_date) );
$time = $myDate->format("H");
if( $time >= 22 || $time <= 6){
$request->timetype = 'night';
}else{
$request->timetype = 'day';
}
$request->book_date = $myDate->format("m/d/Y");
$request->pickup_time = $myDate->format("h:i a");
$request->token = $this->extract_token( $request->token );
var_dump($request );
$finresult = array( 'status' => 'success',
'message' => 'Successfully registered',
'code' => 'registered'
);
print json_encode($finresult);
$this->model_web_service->book($request);
}
and model_web_service:
function book( $request ){
$table = 'bookingdetails';
$insert_data = array(
'username' => $request->token,
'uneaque_id' => $request->uneaque_id,
'purpose' => "Point to Point Transfer",
'pickup_date' => $request->book_date,
'pickup_time' => $request->pickup_time,
'drop_area' => $request->drop_area,
'pickup_area' => $request->pickup_area,
'taxi_type' => $request->taxi_type,
'status' => "Booking",
// 'item_status' => "Pending",
'timetype' => $request->timetype,
'amount' => $request->amount,
'km' => $request->km
);
$this->insert_table($insert_data, $table);
}
i want to change if for read php status array (success)
plz help me for fixing this code

Jquery ajax function fails with no reason

I have a web based mobile android application. I built it with php + jquery + mysql. An ajax code fails but no reason. Therefore it returns 'Try again'. Unfortunately I can not debug it in the application. Here is the code:
$('.get-order-button').live('click', function() {
var musteritel = $('#musteritel').val(), musteriad = $('#musteriad').val(), musteriadres = $('#musteriadres').val(), musterinotu = $('#siparisnotu').val(), odemesekli =$('#odemesekli option:selected').val() ;
if(musteritel != ''){
$.ajax({
type : 'POST',
url : '/enfes/temp-order-sent.php', timeout: 10000,
cache : false,
data : 'musteritel='+musteritel+'&musteriadres='+musteriadres+'&musterinotu='+musterinotu+'&odemesekli='+odemesekli+'&musteriad='+musteriad,
dataType : 'json',
beforeSend : function() {
showDialog('Yükleniyor...')
},
whileLoading: function(xhr) {
if (xhr && xhr.readyState != 4)
xhr.abort()
}
}).always(function() {
closeDialog()
}).fail(function() {
showToastShort('Try again.');
}).done(function(r) {
if(r.s==1){
$.each(r.u, function( index, value ) {
unsetMyCookie(index);
});
$('#detail').remove();
$('.basket-added-btn span').text('0');
basketStatus = 0;
showToastLong(r.m);
window.location.hash = 'home';
}else
showToastShort(r.m);
});
}
return false
});
And here is the php code:
<?php
session_start();
include_once 'class.render.php';
include_once 'class.order.php';
$kendim = new render();
if(isset($_SESSION["id"]) && isset($_POST['musteritel'])) {
$kendiId = $_SESSION["kendiId"];
$uniqueIdentifier = $_SESSION["uniqueIdentifier"];
if(isset($_COOKIE)){
$order = new order();
$musteritel = $order->validTel($_POST['musteritel']);
$musteriad = $order->cleanStr($_POST['musteriad']);
$musteriadres = $order->cleanStr($_POST['musteriadres']);
$musterinotu = $order->cleanStr($_POST['musterinotu']);
$odemesekli = $order->cleanStr($_POST['odemesekli']);
$return = array('s' => 0, 'm' => 'Siparis gonderilemedi. Bilgilerinizi kontrol ediniz.');
$ordersent = $order->addOrder($musteritel, $musteriad, $musteriadres, $musterinotu, $odemesekli);
if($musteritel == "") {
$return = array('s' => 1, 'm' => 'Telefon numaranızı hatalı girdiniz.');
} else {
if($ordersent){
$return = array('s' => 1, 'm' => 'Siparisiniz bize ulasmistir.', 'u' => $order->basket);
}else
$return = array('s' => 0, 'm' => 'Siparis gonderilemedi. Bilgilerinizi kontrol ediniz.');
}
}else
$return = array('s' => 0, 'm' => 'Siparis sepetiniz bos.');
}else
$return = array('s' => 0, 'm' => 'Telefon numaranızı yazmalisiniz.');
echo json_encode($return);
?>
Why does it fail?

PHP parse Meta Tags of an aspx page failure

In my project I have a PHP function that parses an HTML page and retrieves meta tags correctly. When I run my function for an aspx page this fails and doesn't create return data even though the aspx page in question has correctly set the meta tags.
The function is:
function getUrlData($url)
{
$result = false;
$contents = getUrlContents($url);
if (isset($contents) && is_string($contents))
{
$title = null;
$metaTags = null;
preg_match('/<title>([^>]*)<\/title>/si', $contents, $match );
if (isset($match) && is_array($match) && count($match) > 0)
{
$title = strip_tags($match[1]);
}
preg_match_all('/<[\s]*meta[\s]*name="?' . '([^>"]*)"?[\s]*' . 'content="? ([^>"]*)"?[\s]*[\/]?[\s]*>/si', $contents, $match);
if (isset($match) && is_array($match) && count($match) == 3)
{
$originals = $match[0];
$names = $match[1];
$values = $match[2];
if (count($originals) == count($names) && count($names) == count($values))
{
$metaTags = array();
for ($i=0, $limiti=count($names); $i < $limiti; $i++)
{
$metaTags[$names[$i]] = array (
'html' => htmlentities($originals[$i]),
'value' => $values[$i]
);
}
}
}
$result = array (
'title' => $title,
'metaTags' => $metaTags
);
}
return $result;
}
function getUrlContents($url, $maximumRedirections = null, $currentRedirection = 0)
{
$result = false;
$contents = #file_get_contents($url);
// Check if we need to go somewhere else
if (isset($contents) && is_string($contents))
{
preg_match_all('/<[\s]*meta[\s]*http-equiv="?REFRESH"?' . '[\s]*content="?[0-9]*;[\s]*URL[\s]*=[\s]*([^>"]*)"?' . '[\s]*[\/]?[\s]*>/si', $contents, $match);
if (isset($match) && is_array($match) && count($match) == 2 && count($match[1]) == 1)
{
if (!isset($maximumRedirections) || $currentRedirection < $maximumRedirections)
{
return getUrlContents($match[1][0], $maximumRedirections, ++$currentRedirection);
}
$result = false;
}
else
{
$result = $contents;
}
}
return $contents;
}
How is it possible to read meta tags from aspx pages?
Thanks in advance
AM
There might be a easier way to do this using get_meta_tags
e.g.
<?php
// Load
$tags = get_meta_tags('http://www.example.com/');
// Debug
echo "<pre>";
print_r($tags);
echo "</pre>";
?>

Categories

Resources