php JSON to JQuery - php

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);
}

Related

datatables format values with text align

I am using jQuery data tables and fill the data via ajax as json:
https://datatables.net/examples/ajax/simple.html
var tbl = $('.mytbl').DataTable({
"ajax": {
url: "ajax/getData.php",
type: "POST"
}
});
The response of getData.php will be like this:
$myArray['data'][] = array(
"Value 1",
"Value 2",
"Value 3"
}
echo json_encode($myArray);
This works fine:
But how can I define that - for example - value 2 should be text-align right in my table?
Try this
var tbl = $('.mytbl').DataTable({
"ajax": {
url: "ajax/getData.php",
type: "POST"
},
'columnDefs': [{
"targets": 1,
"className": "text-right",
}]
});
You can use render method available in Datatables.
{
data: 'value 2 column',
render: function ( data, type, row ) {
return `<span style="text-align:right">${data}</span>`;
}
}
You can also use css if all column values are right aligned.

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>

Python equivalent to PHP Post

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)})

how to parse array from json returned from php

I have an index.html file that calls main.php which returns a json object just fine.
main.php returns this
{
"products": [
{
"id": "1",
"txt": "Bar",
"image": "",
"page": ""
},
{
"id": "2",
"txt": "Car",
"image": "",
"page": ""
},
{
"id": "3",
"txt": "Far",
"image": "",
"page": ""
}
],
"success": 1
}
in Java there is json.getJSONArray(TAG_PRODUCTS);
but.... I am using HTML and javascript here...
so in my html file I have the following
how do I pull the products array out of my json returned data?
$.ajax({
type: 'POST',
dataType: 'json',
url: 'http://localhost:8888/HelloWorld/main.php',
contentType: "application/json; charset=utf-8",
success: function (data) {
var names = data
$('sa_content').append('<select name="input_4">');
$.each(data, function(index, element) {
alert( "index: " + index + ", element.cf_id: " + element );
});
$('sa_content').append('</select>');
},
error: function(){
$('#sa_content').append('<li>There was an error loading the feed');
}
});
When I run the index.html page I get the following alerts
index = products, element = [object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
and
index = success, element = 1
So how do I pull the products array out of the json and iterate through it to get the values of id, txt, image, page?
Thanks in advance for your time.
Dean-O
Try using this as the success function:
function (data) {
var products = data.products;
for (var i = 0; i < products.length; i++) {
var product = products[i];
alert(product.id + " " + product.txt + " " + product.image + " " + product.page);
}
}
It should iterate through all the products and alert you the data.
Then you can modify the code to suit your needs.
You either use JSON.parse, or simply eval('(' + json + ')'); if you are certain the code is safe.
You're getting an array of products, so you want to iterate over that array:
success: function (data) {
var names = data
for(i = 0; i < data.products.length; i++) {
//Do what you want.
var id = data.products[i].id;
}
}
If your page returns ONLY json, then the XHR object that comes back from your jquery ajax should contain a javascript object constructed from that data. If that is not the case, something is wrong with your page, such as returning more than a json encoded string.

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