Formatting json data to work in Flot - php

Is there anyway to convert this json data:
[
{
"year":"1999",
"value":"3.0"
},
{
"year":"2008",
"value":"0.9"
}
]
to like this:
{
"data": [[1999, 3.0], [2008, 0.9]]
}
Check type of values ("3.0" and 3.0, string and integer).
I am having hard time to figure this out, or is it even possible.
This is how I get the json data:
I have "data" table in my database where are "year" and "value" columns, I get them from database like:
$sql = mysql_query("SELECT * FROM data");
$rows = array();
while($r = mysql_fetch_assoc($sql)) {
$rows[] = $r;
}
$encodedJson = json_encode($rows);
$encodedJson = json_encode($rows);
print $encodedJson;
I am trying to create a graph from my data, and json data must be formated properly to work in Flot.
All help is appreciated!

You could map your array of objects into an multidimensional array:
var mapped = originalData.map(function (obj) {
return [ parseInt(obj.year, 10), parseFloat(obj.value) ];
});
var newData = {
data: mapped
};

Possible solution
var a = [
{
"year":"1999",
"value":"3.0"
},
{
"year":"2008",
"value":"0.9"
}
];
var b = [];
$.each(a, function(_index, _item){
var c = [_item["year"], _item["value"]];
b.push(c);
});
console.log(b)

try this.
PHP:
$sql = mysql_query("SELECT * FROM data");
$rows = $sql->results_array();
$return_args = array();
foreach($rows as $row){
$tmp[0] = $row['year'];
$tmp[1] = $row['value'];
array_push($return_args,$tmp);
}
$encodedJson = json_encode($return_args);
print $encodedJson;

Related

json_encode for more than 2 arrays

I have 2 tables to be retrieved from database with 2 different queries and needs to be encoded in json and send to ajax.The issue is I am not able to pass 2 json's to ajax .
I have tried with echo json_encode(array($data1,$data2)); but it is not working.
//My php code
$query = $db->query("select * from table1 where valu1='".$value1."'");
while ($row = $query->fetch_assoc()) {
$data1['value1'] = $row['value1'];
$data1['value2'] = $row['value2'];
}
$query = $db->query("select * from table2 where value2='".$value2."' ");
while ($row = $query->fetch_assoc()) {
$data2['value2'] = $row['value2'];
$data2['value3'] = $row['value3'];
}
echo json_encode(array($data1,$data2));
//My AJAX code
$(document).ready(function(){
$('#Form').submit(function(e){
e.preventDefault(); // stops the form submission
$.ajax({
url:$(this).attr('action'), // action attribute of form to send the values
type:$(this).attr('method'), // method used in the form
data:$(this).serialize(), // data to be sent to php
dataType:"json",
success:function(data){
//main
alert(data.value1);
},
error:function(err){
alert(err);
}
});
});
});
Kindly help in solving this issue.Thanks in advance
In PHP:
echo json_encode(array($data1, $data2));
In AJAX:
var data1 = data[0];
var data2 = data[1];
$.each(data1, function() {
console.log(this.value1 + ',' + this.value2);
});
$.each(data2, function() {
console.log(this.value2 + ',' + this.value3);
});
EDIT:
After a whole year, I just noticed that the initial PHP code was wrong, because the loop for the sql result would overwrite each time the values of the array. So, the correct one is this:
$query = $db->query("select * from table1 where valu1='".$value1."'");
while ($row = $query->fetch_assoc()) {
$data1[] = array('value1' => $row['value1'], 'value2' => $row['value2']);
}
$query = $db->query("select * from table2 where value2='".$value2."' ");
while ($row = $query->fetch_assoc()) {
$data2[] = array('value2' => $row['value2'], 'value3' => $row['value3']);
}
echo json_encode(array($data1,$data2));
Your code is fine, you just have to handle the two arrays within your success function:
success: function(data){
var object1 = data[0];
var object2 = data[1];
// Do whatever you like to do with them
}

Angular Display Data From Array

I am new to angularJS and has very few knowledge on javascript.
I am trying to retrieve data from database by using the $http.post method. below is what I get from the .php file.
[{
"ticketid": "1484637895",
"categoryid": "1",
"subcategoryid": "2",
"ciphonenum": "01814149028",
"calldescription": "The customer wanted to know all the SKU of Bashundhara Baby Diaper and he requested to inform him through the mail.",
"ccrreply": "CCR sent him all SKU of Diaper including the M.R.P.",
"ccraction": "N\/A",
"output": "N\/A",
"remarks": "N\/A",
"contactinfoname": "MD.Masud",
"ciaddress": "Banani,DOHS\nDhaka."
}]
Here is what my php file looks like
<?php
$data = json_decode(file_get_contents("php://input"));
require 'db-config.php';
$ticketid = $data->id;
$sql = "SELECT t.ticketid, t.categoryid, t.subcategoryid, td.ciphonenum, td.calldescription, td.ccrreply,
td.ccraction, td.output, td.remarks, ci.contactinfoname, ci.ciaddress FROM ticketdetails td
INNER JOIN tickets t on t.ticketid = td.ticketid
INNER JOIN contactinfodetails ci ON ci.ciphonenum = td.ciphonenum WHERE t.ticketid = '$ticketid'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$data = array();
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
} else {
echo "0 results";
}
echo json_encode($data);
$conn->close();
?>
Below is the function in angularjs which generate the post request
$scope.showTicket = function() {
var id = $routeParams.id;
$http.post('api/showTicket.php',{'id':id}).then(function(response){
$scope.ticket = response.data;
console.log($scope.ticket);
});
};
I want display only the ticketid and calldescription from the array but whenever I assign value like
$scope.ticketid = $scope.ticket.ticketid;
it says undefined variable. Please help....
Your JSON is an array of objects, and not an object.
So instead of doing $scope.ticketid = $scope.ticket.ticketid, try:
$scope.ticketid = $scope.ticket[0].ticketid;
As your array only contains one object, it is probably the solution...

$.each() loop through json not looping

i have an ajax call that gets back json i am trying to send the items returned to specific input text id's.
This is the ajax:
$.ajax({
url: "php/myfirstfile.php",
type: "POST",
data: $("#frameroof").serialize(),
cache: false,
dataType: "json",
success: function (json) {
$.each(json, function () {
$.each(json, function (key, value) {
/// do stuff
$('#' + key ).val(value);
});
});
}
});
This is what is returned: [{"a-frame":"100"}][{"vertical":"350"}]
it looks im getting 2 arrays when i need one to loop over. Im not sure.
Here is the php
if(isset($_POST["cart"])){
$frameArray = ($_POST["cart"]);
if(is_array($frameArray)){
foreach($frameArray as $row){
$catalogue = $row['catalogue'];
$certification = $row['certification'];
$catagory = $row['catagory'];
$subcatagory = $row['subcatagory'];
$length = $row['length'] ;
$sql = "SELECT `price` AS '$subcatagory' FROM `products` WHERE `catalogue_id` = '$catalogue' AND `certification` = '$certification' AND `catagory` = '$catagory' AND `sub_catagory` = '$subcatagory' AND `length` = '$length' ";
$result = $short_connect->query($sql);
if (($result) && ($result->num_rows > 0)) {
$results = array();
//convert query result into an associative array
while ($row = $result->fetch_assoc()) {
$results[] = $row;
}
//dump all data from associative array converted from query result
echo (json_encode($results,true));
$result->free();
}
}
}
}
$short_connect->close();
I believe your problem is pretty simple. Inside of your loop you're initializing the results array and you're outputting it. This causes a new results array to be created, serialized to JSON, and outputted for every iteration of the loop. Thus what you're sending the browser is not JSON, but several chunks of JSON all run together.
This is the basic idea of what you need to be doing:
<?php
// Initialize the output data
$results = array();
foreach($something as $a_something) {
$results[] = do_something_to($a_something);
}
//Serialize and send the output data
echo (json_encode($results,true));
Rearranging your code with that pattern in mind produces this (which ought to work for you, and will return an empty array to the browser if your if conditions aren't met or the query doesn't return anything):
<?php
// Initialize the output data
$results = array();
if(isset($_POST["cart"])){
$frameArray = ($_POST["cart"]);
if(is_array($frameArray)){
foreach($frameArray as $row){
$catalogue = $row['catalogue'];
$certification = $row['certification'];
$catagory = $row['catagory'];
$subcatagory = $row['subcatagory'];
$length = $row['length'] ;
$sql = "SELECT `price` AS '$subcatagory' FROM `products` WHERE `catalogue_id` = '$catalogue' AND `certification` = '$certification' AND `catagory` = '$catagory' AND `sub_catagory` = '$subcatagory' AND `length` = '$length' ";
$result = $short_connect->query($sql);
if (($result) && ($result->num_rows > 0)) {
//convert query result into an associative array
while ($row = $result->fetch_assoc()) {
//Add to the output data
$results[] = $row;
}
$result->free();
}
}
}
}
$short_connect->close();
//Serialize and send the output data
//dump all data from associative array converted from query result
echo (json_encode($results,true));

json_encode in php

i have this script and it works, but not as i expected. I need to assign an array of values with differents names, now all $arr[] are named "valor"
{"valor":"20"},{"valor":"50"}
i need
{"valor1":"20"},{"valor2":"50"}
the script
$query = mysql_query("SELECT valor FROM grafico") or die(mysql_error());
$arr = array();
while($row = mysql_fetch_assoc($query)) {
$arr[] = $row;
}
echo json_encode($arr);
in ajax
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("button").click(function(){
jQuery.ajax({
url: "chart.php",
dataType: "json",
success: function(json){
var msg = "Nome: " + json.valor1+ "\n";
msg += "Sobrenome: " + json.valor2 + "\n";
alert(msg);
}
});
});
});
</script>
the problem is: I need to create a loop that create uniques names, as value1, value2, value3
like
$arr['valor1'] = "Evandro";
i tried a loop- for, but i get an error of memory
thanks
Try this:
$query = mysql_query("SELECT valor FROM grafico") or die(mysql_error());
$arr = array();
$i = 1;
while($row = mysql_fetch_assoc($query)) {
$arr[] = array("valor{$i}" => $row["valor"]);
++$i;
}
echo json_encode($arr);
Should work. Alternatively if you want to make it so it works with current callback change the $arr[] = line to the following:
$arr["valor{$i}"] = $row["valor"];
$index = 1;
while($row = mysql_fetch_assoc($query)) {
$key = 'valor'.index;
$arr[$key] = $row;
$index++;
}
Does that give you a memory error? It shouldn't.

php to js array convert with jquery's ajax

Im trying to convert 5 PHP arrays to 5 js arrays.
I used to transfer php variables to js variables with json like this:
$return['variable'] = $variable;
echo json_encode($return);
And then fetch it as json object on the js side like this:
success : function(data) {
alert(data.variable);
}
now things are a bit more complicated, i need to transfer these 5 php arrays from a php script to my js script as 5 js arrays:
PHP arrays:
$i = 0;
while ($location = mysql_fetch_array($get_locations)) {
$location_full_name[$i] = $location['loc_full_name'];
$location_main_name[$i] = $location['loc_main_name'];
$location_sub_name[$i] = $location['loc_sub_name'];
$location_anchor_id[$i] = $location['loc_anchor_id'];
$location_type[$i] = $location['loc_type'];
$i++;
}
and fill these corresponding arrays:
var location_full_name = new Array();
var location_main_name = new Array();
var location_sub_name = new Array();
var location_anchor_id = new Array();
var location_type = new Array();
i dont know how to do this. hope i can get some help :)
regards,
alexander
Maybe if you post what returns in "data" so we can help you more (i think). hehe.
I suggest, for your php code, where you set the data into the arrays:
$i = 0;
$rsl = array();
while ($location = mysql_fetch_array($get_locations)) {
$rsl[$i]['full_name'] = $location['loc_full_name'];
$rsl[$i]['main_name'] = $location['loc_main_name'];
$rsl[$i]['sub_name'] = $location['loc_sub_name'];
$rsl[$i]['anchor_id'] = $location['loc_anchor_id'];
$rsl[$i]['type'] = $location['loc_type'];
$i++;
}
echo json_encode($rsl);
So to get this on the javascript
// You could do the same... var location = []...
var location_full_name = new Array();
var location_main_name = new Array();
var location_sub_name = new Array();
var location_anchor_id = new Array();
var location_type = new Array();
...
dataType: "json",
success : function(data) {
$.each(data, function(index, arr){
location_full_name[index] = arr['full_name'];
...
});
}
For each of your arrays, store the value returned from json_encode. And/or make them one array/object and do the same.
You can utilize the PHP array that is actually an ordered map. Below is an example:
PHP:
<?php
$location_full_name = array("Google, Inc.", "Siku-Siku.com");
$location_type = array("Google headquarter", "Virtual address");
$ret = array("full_name" => $location_full_name, "type" => $location_type);
echo json_encode($ret);
?>
JavaScript (jQuery):
<script type="text/javascript">
$(function() {
$.get("test.php", function(data) {
console.log(data.full_name[1]); // Prints "Siku-Siku.com".
}, "json");
});
</script>

Categories