Python equivalent to PHP Post - php

I am working with legacy system, and the previous programmer has gone. Here is the test he left and I have no idea how to imitate his test using Python.
Here is test.php
var tHost = "10.1.10.123";
var tExiname = "CloudHM TEST123";
var tIncname = "INC012345";
var tHWname = "aa 1111 0";
var tHwattr = "all";
var tStatus = 0;
var tCteatedat = "2016-05-23 12:20:42";
var d = new Date,
tUpdateat = [d.getFullYear(),
d.getMonth()+1,
d.getDate()].join('-')+' '+
[d.getHours(),
d.getMinutes(),
d.getSeconds()].join(':');
var arr = [{ host: tHost, host_name: tExiname, component_type: tHWname, component_status: tStatus, incident_created: tUpdateat }];
var arr2 =JSON.stringify(arr)
$.ajax({
url: 'http://customer.beenets.net/api/cloudhm/api.php' ,
type: 'POST',
data: { params: arr2 },
success: function(msg) {
//ShowOutput(msg);
alert(JSON.stringify(arr, null, 4));
}
})
I had tried this. Response is 200, but PHP server read no payload
notification_data = [{
"host": i.host,
"host_name": i.host_name,
"incident_created": i.incident_created,
"component_type": i.component_type,
"component_status": i.component_status
}]
response = requests.post(NOC_BEENETS_URL, data=json.dumps(notification_data))
Then I try put params key in front of it
notification_data = [{
"params":{
"host": i.host,
"host_name": i.host_name,
"incident_created": i.incident_created,
"component_type": i.component_type,
"component_status": i.component_status
}
}]
response = requests.post(NOC_BEENETS_URL, data=json.dumps(notification_data))
Server return me 200 and read no payload again.

Edited:
notification_data = [{
"host": i.host,
"host_name": i.host_name,
"incident_created": i.incident_created,
"component_type": i.component_type,
"component_status": i.component_status
}]
r = requests.post(NOC_BEENETS_URL, data = {'params': json.dumps(notification_data)})

Related

Line Chart using Chart js with time data

I am creating a line chart using chartJs by passing date at X-Axis and time (mm:ss) at Y-Axis. I am not sure how to use chartJs with time values.I tried different solutions from stack but none works in my case.
Here is json file
{"label":["08-Aug-2019","11-Aug-2019","22-Aug-2019","25-Aug-2019"],"time":["1:08","1:44","2:27","1:02"],"chart_data":"{\"label\":[\"08-Aug-2019\",\"11-Aug-2019\",\"22-Aug-2019\",\"25-Aug-2019\"],\"time\":[\"1:08\",\"1:44\",\"2:27\",\"1:02\"]}"}
Here is what i am trying to code
<div id="time_chart"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.js"></script>
<script>
let sData = JSON.parse('<?php echo $chart_data; ?>');
let time_ctx = $("#time-chart");
//Line Chart
var time_data = {
labels: sData.label,
datasets: [
{
label: sData.label,
data: sData.time
}
]
};
//options line chart
var time_options = {
responsive: true,
title: {
display: false
},
legend: {
display: false
},
scales: {
yAxes: [{
type: 'time',
time: {
parser: 'm:s',
unit: 'minute',
unitStepSize: 2,
min: '0:0',
max: '30:00',
displayFormats: {
'seconds': 'm.s'
}
},
ticks: {
callback: function(value, index, values) {
//Ticks reverse does not work with time axes so we have to revert in this callback
if (values[values.length - index] != undefined) {
return moment(values[values.length - index].value).format('m.s');
}
}
}
}]
}
};
var chart2 = new Chart(time_ctx, {
type: "line",
data: time_data,
options: time_options
});
</script>
This is what I am getting with this code:
Although I didn't manage to use a time axis for both the x- and y-axes, I managed to create a workaround with a timed x-axis and a linear y-axis.
I parse your time and return the time in seconds (integer). I use this value to display your time and change the format back to mm:ss.
I hope this is what you wanted. I'm not sure you want the axes this way (because in your code you use the y-axis as type "time").
PS: My first post, please feel free to tell me what I can improve.
JSFiddle: https://jsfiddle.net/5837nmyo/
JSBin: https://jsbin.com/yadixolica/1/edit?html,js,output
let sData = {}
sData.label = ["08-Aug-2019","11-Aug-2019","22-Aug-2019","25-Aug-2019"]
sData.time = ["1:08","1:44","2:27","1:02"]
let chartData = {}
chartData.label = sData.label
chartData.time = parseTimeToSeconds(sData.time)
function parseTimeToSeconds(times){
let regex = /(\d*):(\d{2})/gm
let parsedTime = []
for (let x = 0; x < times.length; x++) {
let match = regex.exec(times)
parsedTime.push(parseInt(match[1])*60 + parseInt(match[2]))
}
return parsedTime
}
let time_ctx = document.getElementById('time_chart');
let time_data = {
labels: chartData.label,
datasets: [{
label: chartData.label,
data: chartData.time
}]
};
let time_options = {
responsive: true,
title: {
display: false
},
legend: {
display: false
},
tooltips: {
callbacks: {
label: function(tooltipItem, data){
let value = parseInt(tooltipItem.value)
if (value%60 < 10)
return Math.floor(value/60) + ":" + 0 + value%60
else
return Math.floor(value/60) + ":" + value%60
}
}
},
scales: {
xAxes: [{
type: 'time'
}],
yAxes: [{
ticks: {
min: 0,
max: 1800,
stepSize: 120,
callback: function(value, index, values) {
if (value%60 < 10)
return Math.floor(value/60) + ":" + 0 + value%60
else
return Math.floor(value/60) + ":" + value%60
}
}
}]
}
};
let chart2 = new Chart(time_ctx, {
type: "line",
data: time_data,
options: time_options
});

Receive JSON ENCODED Data from all rows of table from php and show in html table using ajax

I am struggling from a few hours but not getting to any point,neither i am able to find any proper solution for this.
I am trying to retrieve json data(includes rows from table) and show in html table using ajax .The point where i am now is it only show one row when i use the following code but give errors when i try to parse data from all rows:
PHP
if (isset($_POST['groups_per_table'])){
try{
$stmt = $db_con->prepare("SELECT * FROM groups_permissions");
$stmt->execute();
$response = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$response['id'] = $row['id'];
$response['group'] = $row['group'];
$response['restricted_pages'] = $row['restricted_pages'];
$response['restricted_permissions'] = $row['restricted_permissions'];
echo json_encode($response);
}
}
catch(PDOException $e){
echo $e->getMessage();
}
}`
if i use in the query WHERE id=1 (i.e the firt row only)then it display the data correctly:
JS
$( document ).ready(function() {
groups_per_table();
function groups_per_table(){
$.ajax({
type: "POST",
url : '../core/ajaxpdo.class.php',
data: 'groups_per_table='+'givedata',
success: function (response) {
var gp_data = $.parseJSON(response);
console.log(response);
$("#gp_body").html('<tr><td class="text-center"><label id="'+gp_data.id+'" class="csscheckbox csscheckbox-primary"><input type="checkbox"><span></span></label></td><td><strong>'+gp_data.group+'</strong></td><td>'+gp_data.restricted_pages+'</td><td>'+gp_data.restricted_permissions+'</td><td class="text-center"><span class="btn-ripple animate" style="height: 32.2917px; width: 32.2917px; top: -6.81251px; left: 0.3229px;"></span><i class="fa fa-pencil"></i><i class="fa fa-times"></i></td></tr>');
},
error: function() {
alert('There is an error!');
}
});
return false;
}});
I want to show all rows from db in table,it gives following error in console:
CONSOLE LOG
Uncaught SyntaxError: Unexpected token { in JSON at position 76
at Function.parse [as parseJSON] (<anonymous>)
at Object.success (groups-permissions.php:968)
at u (jquery-3.3.1.min.js:2)
at Object.fireWith [as resolveWith] (jquery-3.3.1.min.js:2)
at k (jquery-3.3.1.min.js:2)
at XMLHttpRequest.<anonymous> (jquery-3.3.1.min.js:2)
THE JSON DATA
{"id":"1","group":"group","restricted_pages":"","restricted_permissions":""}{"id":"2","group":"newgroup","restricted_pages":"b","restricted_permissions":"f"}{"id":"3","group":"asd","restricted_pages":"a,b,c,d","restricted_permissions":"e,f,g,h"}
This is SyntaxError in your JSON, which means your JSON is not a valid JSON, your json results should be something like this:
[{
"id": "1",
"group": "group",
"restricted_pages": "",
"restricted_permissions": ""
}, {
"id": "2",
"group": "newgroup",
"restricted_pages": "b",
"restricted_permissions": "f"
}, {
"id": "3",
"group": "asd",
"restricted_pages": "a,b,c,d",
"restricted_permissions": "e,f,g,h"
}]
So what I suggest you to do is to add another array, you can call it $json and push your data to it like so:
Server side (PHP)
// ...
$response = array();
$json = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$response['id'] = $row['id'];
$response['group'] = $row['group'];
$response['restricted_pages'] = $row['restricted_pages'];
$response['restricted_permissions'] = $row['restricted_permissions'];
array_push($json, $response);
}
echo json_encode($json);
// ...
Client side (JavaScript)
$( document ).ready(function() {
groups_per_table();
function groups_per_table(){
$.ajax({
type: "POST",
url : '../core/ajaxpdo.class.php',
data: 'groups_per_table='+'givedata',
success: function (response) {
var gp_data = $.parseJSON(response);
for(var i = 0; i < gp_data.length; i++) {
$("#gp_body").html('<tr><td class="text-center"><label id="'+gp_data[i].id+'" class="csscheckbox csscheckbox-primary"><input type="checkbox"><span></span></label></td><td><strong>'+gp_data[i].group+'</strong></td><td>'+gp_data[i].restricted_pages+'</td><td>'+gp_data[i].restricted_permissions+'</td><td class="text-center"><span class="btn-ripple animate" style="height: 32.2917px; width: 32.2917px; top: -6.81251px; left: 0.3229px;"></span><i class="fa fa-pencil"></i><i class="fa fa-times"></i></td></tr>');
}
},
error: function() {
alert('There is an error!');
}
});
return false;
}
});
Make a loop to put your data in the DOM:
var testObject = [{
"id": "1",
"group": "group",
"restricted_pages": "",
"restricted_permissions": ""
},
{
"id": "2",
"group": "newgroup",
"restricted_pages": "b",
"restricted_permissions": "f"
},
{
"id": "3",
"group": "asd",
"restricted_pages": "a,b,c,d",
"restricted_permissions": "e,f,g,h"
}
];
function putdataToDom(gp_data) {
$("#gp_body").html('');
for (var i = 1; i < gp_data.length; i++) {
$("#gp_body").append('<tr><td class="text-center"><label id="' + gp_data[i].id + '" class="csscheckbox csscheckbox-primary"><input type="checkbox"><span></span></label></td><td><strong>' + gp_data[i].group + '</strong></td><td>' + gp_data[i].restricted_pages + '</td><td>' + gp_data[i].restricted_permissions + '</td><td class="text-center"><span class="btn-ripple animate" style="height: 32.2917px; width: 32.2917px; top: -6.81251px; left: 0.3229px;"></span><i class="fa fa-pencil"></i><i class="fa fa-times"></i></td></tr>');
}
}
putdataToDom(testObject);
$(document).ready(function() {
groups_per_table();
function groups_per_table() {
$.ajax({
type: "POST",
url: '../core/ajaxpdo.class.php',
data: 'groups_per_table=' + 'givedata',
success: function(response) {
var gp_data = $.parseJSON(response);
console.log(response);
putdataToDom(gp_data);
},
error: function() {
alert('There is an error!');
}
});
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="gp_body" border=1></table>

php JSON to JQuery

I am creating Google chart using MYSQL data through PHP. Below is the part of jQuery.
$.ajax({
method: 'GET',
//dataType: 'JSON',
url: "/php/abc.php",
success: function (data1) {
var data = new google.visualization.DataTable();
// Add legends with data type
data.addColumn('string', 'type');
data.addColumn('number', 'value');
//Parse data into Json
var jsonData = $.parseJSON(data1);
//var jsonData = (data1);
for (var i = 0; i < jsonData.length; i++) {
alert (jsonData[i].length);
alert (jsonData[i].type);
data.addRow([jsonData[i].type, parseInt(jsonData[i].value)]);
}
I am getting below output from php when i check direct php page on browser
{"type":"New_Userstory","value":"10"}{"type":"Active_Userstory","value":"20"}{"type":"Resolved_Userstory","value":"30"}{"type":"Closed_Userstory","value":"40"}
but through json it is not showing anything, says incorrect character '{'. When i have used header('Content-Type: application/json'); or dataType: 'JSON', this eror is gone but result is "undefined" any other way to get this JSON ?
This is not the correct JSON output.
{"type":"New_Userstory","value":"10"}{"type":"Active_Userstory","value":"20"}{"type":"Resolved_Userstory","value":"30"}{"type":"Closed_Userstory","value":"40"}
The correct JSON output would be
[
{
"type": "New_Userstory",
"value": "10"
},
{
"type": "Active_Userstory",
"value": "20"
},
{
"type": "Resolved_Userstory",
"value": "30"
},
{
"type": "Closed_Userstory",
"value": "40"
}
]
According to your PHP Code, here is what you need to change.
$this->temp_sql_display = "SELECT * FROM SalesSummary";
try {
$result = $this->hookup->query($this->temp_sql_display);
while ($row = $result->fetch_assoc())
{
$this->json[] = $row;
}
echo json_encode($this->json);
}

Flot Charts using SQL Server db with multiple y axis

This is my first post, apologies if I've asked a question a number of people have already done so. I don't see the answer I need in other posts.
I'm using Flot Charts and have a SQL Server db, I've got a php file that will connect to the db and return all the values within the sql in an array.
<?php
$server = "XXXX";
$database = "XXXX";
$user = "ReportsUser";
$pwd = "ReportsUser";
$cnn = odbc_connect("Driver={SQL Server Native Client 10.0};Server=$server;Database=$database;", $user, $pwd);
if(!$cnn)
{
echo "error in connecting";
}
$sql = odbc_exec($cnn, "
SELECT Months
,Referrals
,ProjectedVol
FROM mis.ReferralsBudgetvsActual
WHERE Months <= MONTH(GETDATE())
");
while($result = odbc_fetch_array($sql))
{
$allreferrals[] = array($result['Months'],$result['Referrals'],$result['ProjectedVol']);
}
echo json_encode(($allreferrals), JSON_NUMERIC_CHECK);
exit;
?>
This works well and produces the array as below
[[1,5981,7465],[2,5473,6962],[3,4974,7391],[4,5731,6985],[5,5891,7080],[6,5168,7136],[7,5551,7543],[8,4427,7242],[9,4617,7204],[10,4807,7642]]
Now, when it all comes together in the jquery file, this is where I end up getting stuck. I don't see where it pulls any other columns back apart from the first data column, how can this be done?
// document ready function
$(document).ready(function() {
var chartColours = ['#88bbc8', '#ed7a53', '#9FC569', '#bbdce3', '#9a3b1b', '#5a8022', '#2c7282'];
// function for refreshing shiftstats chart
make_chart();
function make_chart() {
$.ajax({
cache: 'false',
type: 'GET',
dataType: 'json',
url: "test.php",
success: function(data) {
var d1 = data;
var d2 = data;
//define placeholder class
var placeholder = $(".shifts-chart");
//graph options
var options = {
grid: {
show: true,
aboveData: true,
color: "#3f3f3f" ,
labelMargin: 5,
axisMargin: 0,
borderWidth: 0,
borderColor:null,
minBorderMargin: 5 ,
clickable: true,
hoverable: true,
autoHighlight: true,
mouseActiveRadius: 20
},
series: {
grow: {
active: false,
stepMode: "linear",
steps: 50,
stepDelay: true
},
lines: {
show: true,
fill: false,
lineWidth: 4,
steps: false
},
points: {
show:true,
radius: 5,
symbol: "circle",
fill: true,
borderColor: "#fff"
}
},
legend: {
position: "ne",
margin: [0,-25],
noColumns: 0,
labelBoxBorderColor: null,
labelFormatter: function(label, series) {
// just add some space to labes
return label+' ';
}
},
yaxis: { min: 0 },
xaxis: {ticks:11, tickDecimals: 0},
colors: chartColours,
shadowSize:1,
tooltip: true, //activate tooltip
tooltipOpts: {
content: "%s : %y.0",
shifts: {
x: -30,
y: -50
}
}
};
$.plot(placeholder,
[{
label: "Referrals",
data: d1,
lines: {fillColor: "#f2f7f9"},
points: {fillColor: "#88bbc8"}
},
{
label: "ProjectedVol",
data: d2,
lines: {fillColor: "#f2f7f9"},
points: {fillColor: "#88bbc8"}
}
], options);
}
});
}
});
Thanks
You'll need to change your php array creation to properly format the data into two series:
$d1 = array();
$d2 = array();
while($result = odbc_fetch_array($sql))
{
array_push($d1, array($result['Months'], $result['Referrals']));
array_push($d2, array($result['Months'], $result['ProjectedVol']));
}
$allreferrals = array($d1, $d2);
echo json_encode(($allreferrals), JSON_NUMERIC_CHECK);
This should return it as an array of arrays:
[
[[1,5981],[2,5473],[3,4974],[4,5731],[5,5891],[6,5168],[7,5551],[8,4427],[9,4617,7204],[10,4807]],
[[1,7465],[2,6962],[3,7391],[4,6985],[5,7080],[6,7136],[7,7543],[8,7242],[9,7204],[10,7642]]
]
(Hopefully I have the syntax correct, I'm not a fan of php)
Update from comment
If you are returning a slew of series, you might be better returning an associative array from PHP:
$allreferrals = array('ref' => array(), 'projVol'=> array());
while($result = odbc_fetch_array($sql))
{
array_push($allreferrals['ref'], array($result['Months'], $result['Referrals']));
array_push($allreferrals['projVol'], array($result['Months'], $result['ProjectedVol']));
}
echo json_encode(($allreferrals), JSON_NUMERIC_CHECK);
Then back in the javascript:
$.plot(placeholder,
[{
label: "Referrals",
data: data["ref"]
},
{
label: "ProjectedVol",
data: data["projVol"]
}],
options);

handling json data in php from jquery ajax

I created a json with this structure
var data =
{
"people": [
{ "name" : "John", "id" : 1 },
{ "name" : "Marc", "id" : 2 }
]
}
Now here's how i send the data to the php
var ordenDeCompra = JSON.stringify(data);
$.post("../Backend/ordenesDeCompra.php",
{
ventas: data,
idcliente : $('#sltCliente').val(),
subtotal: subtotalfactura
},
respuesta);
Now when i tried to handle the data in the php it doesn't have any values, i know that the values are sending well, because i see the data sending with charles debugging proxy.
This is how i tried the get the value in the php
$array = json_decode(stripslashes($_POST['ventas']), true);
Am i sending the values corrected??
change
ventas: data,
to
ventas: ordenDeCompra,
Use:
var ordenDeCompra = JSON.stringify(data);
$.post("../Backend/ordenesDeCompra.php",
{
ventas: ordenDeCompra,
idcliente : $('#sltCliente').val(),
subtotal: subtotalfactura
},
respuesta);
var ordenDeCompra = JSON.stringify(data);
$.post("../Backend/ordenesDeCompra.php",
{
ventas: ordenDeCompra, // shouldn't it be ordenDeCompra than data
idcliente : $('#sltCliente').val(),
subtotal: subtotalfactura
},
respuesta);

Categories