I have an array that is created in PHP, and then encoded into my javascript via JSON.
The Array is defined here:
$stmt -> bind_result($match_id, $hero, $mmr);
while($stmt -> fetch()){
$grapharray[] = array($hero => $mmr);
}
and JSON encoded here:
$grapharray_labelled = array(
"label" => "MMR Over time",
"data" => $grapharray
);
and here:
var graphdata = <?php echo JSON_encode($grapharray_labelled); ?>;
The output when I run my webpage is that graphdata =:
{
"label":"MMR Over time",
"data":[
{"Rubick":6524},
{"Lion":6550},
{"Magnus":6565},
{"Keeper of the Light":6566}
]
}
However I would like it to be like this:
{
"label":"MMR Over time",
"data":[
["Rubick", 6524],
["Lion", 6550],
["Magnus", 6565],
["Keeper of the Light", 6566]
]
}
Reason:
I would like to change the format because I am trying to get flot to work, and flot accepts an array of arrays as the datatype.
Otherwise: Is there a better way to transfer an array from PHP to JavaScript with my desired format?
Change this:
$grapharray[] = array($hero => $mmr);
TO:
$grapharray[] = array($hero, $mmr);
Related
In the sever side i have an array with structure like that:
array ('_1489378560544_544' => array (
'customer_group_id' => '0',
'permission_id' => 'disable_products_price',),
'_1489740032764_764' => array (
'customer_group_id' => '',
'permission_id' => '',),)
So now in the client side i want to create an javascript array with the same structure to server side. Is there any possible way to do that?
So after i got all data separately how can i organize my array look like this
var arr = [{_1489378560544_544 : [customer_group_id : 0 , permission_id : 'permission_id'] }]
Here is my javascript get data function:
$('#category_permission > tbody > tr').each(function() {
var id = $(this).attr("id");
var customer_group_id = $(this).children('td:first').children('select:first').val();
var permission_id = $(this).children('td:nth-child(2)').children('select:first').val();
});
Thanks for your help.
You can use json_encode to convert your PHP array to a JSON string and use JSON.parse() to obtain the equivalent Javascript object. Take a look here: https://www.w3schools.com/js/js_json.asp
Something like this :
var arr = [{_1489378560544_544 : [customer_group_id : 0 , permission_id : 'permission_id'] }]
in your php view file
jsStr = '<?php echo json_encode($array)?>'
jsObj = JSON.parse(jsStr);
console.log(jsObj.keyname);
like that all keys can be accessed to get the value. javascript don't support alphanumerical keys for array.
Answer from #Mistalis should help.
I am currently in a bind, JQuery is unable to parse the following json strings
{ "query":"Unit",
"suggestions":
[ {"value":"Mr Ruto Kimutai ","data":88},{"value":"Mr Kimani Karanja","data":79} ] }
{"query":"Unit",
"suggestions":
[{"value":"Mr Ruto Kimutai ","data":88},{"value":"Mr Kimani Karanja","data":79}]}
The above strings when parse through JSON.parse create the following arror:
SyntaxError: JSON.parse: unexpected non-whitespace character after
JSON data at line 1 column 112 of the JSON data
The PHP code which creates the string above is this:
public function getCustomerSuggestions($name){
$customers = $this->model->where('name','LIKE','%'.$name.'%')->show();
if(count($customers)>=1){
foreach($customers as $customer){
$list[] = ['value' => ucfirst($customer->name),'data' => $customer->id];
}
}
else{
$list[] = ['value' => 'No Customers Found', 'data'=> NULL];
}
$full_list['query'] = 'Unit';
$full_list['suggestions'] = $list;
return json_encode($full_list);
}
As you can see I am using the function json_encode to create the JSOn string so there should be no issue but it still doesnt work.
Edit
The json is sent using an autocomplete tool called DevBridge Autocomplete which takes the JSON strings and creates a suggestion list. The code I am using is
$('input[name=\"customer\"]').devbridgeAutocomplete({
serviceUrl: '".SITE_PATH."/ajax/admin/quotes/getcustomer',
minChars: 1,
onSearchStart: function (query){
var searchinput = $(this).val();
$('.autocomplete-suggestions').html('Searching: '+searchinput);
},
onSelect: function(suggestion){
var selection = $(this).val(suggestion.value);
$('input[name=\"customerid\"]').val(suggestion.data);
$.get('".SITE_PATH."/ajax/admin/quotes/getcustomerdetails',{id: suggestion.data},
function(response){
var obj = $.parseJSON(response);
$.each(obj, function(key, value){
$('#'+key).val(value);
});
});
}
});
It seems you have two JSON objects after each other. That's simply invalid. There can only be a single value at the root of a JSON "document". If you want to send down multiple objects, you need to put them in an array.
It seems getCustomerSuggestions is called multiple times and the return value of each call is returned to the client. Instead, the method should return an array, the caller should collect the return values in an array and JSON encode that array.
Well, your JSON string is NOT valid.
It should be,
[
{ "query":"Unit",
"suggestions":
[ {"value":"Mr Ruto Kimutai ","data":88},{"value":"Mr Kimani Karanja","data":79} ] }
,
{"query":"Unit",
"suggestions":
[{"value":"Mr Ruto Kimutai ","data":88},{"value":"Mr Kimani Karanja","data":79}]}
]
But as Felix Kling said, check your PHP code.
Here is the server side code I am trying to send json
$x = array();
$timestamp = strtotime('22-09-2008');
$x["x"] = $timestamp;
$x["y"] = 22;
$val = '[{ "name": "weight", "dataPoints": ['.json_encode($x).'] }]';
echo json_encode($val);
So output for above code looks like
"[{ \"name\": \"weight\", \"dataPoints\": [{\"x\":1222041600,\"y\":22}] }]"
Below is the client side code I get the data via Jquery getJSON
var jqxhr = $.getJSON( "https://domain/gettracker.php?id="+id, function(data) {
console.log(data);
})
I suppose getJson converts json to object automatically , but it logs the raw json like below
"[ { name: "weight", dataPoints: [{"x":1222041600,"y":22}] } ]"
I tried to do json parse , but i get error.
I guess I am not sending the data properly via php.Can some one guide me ?
Your JSON string is not valid - the property names should be enclosed in double quotes - ", and you don't need to encode the string again.
$val = '[{ "name": "weight", "dataPoints": ['.json_encode($x).'] }]';
echo $val;
Or better yet, use json_encode to create the string for you:
$data = array(
'name' => 'weight',
'dataPoints' => $x
);
echo json_encode($data);
I've got the following code:
$data = array(
"1421852400000" => "100",
"1421856000000" => "110",
);
$newData = json_encode($data);
echo $newData;
This is what comes out (using the PHP code above)
{"1421852400000":"100","1421856000000":"110"}
But what I really need is the array in this format:
[
[1421852400000, 100],
[1421856000000, 110],
[1421859600000, 125]
]
Also, the first value is a timestamp (being used in Flot charts) and the second value is for the y axis of the graph.
In javascript I get these values like this:
var visit = JSON.parse(xmlhttp.responseText);
When I simply display the desired format it works, but when I try the PHP things it's giving me some odd results..
The problem is that when I use a PHP array and encode it then echo that and fetch it with Ajax and parse it with js it's not in the right format and thus it does not work..
How would I get the desired result? Thanks in advance!
This Is what you should put in the $data.
$data = array(
array("1421852400000", "100"),
array("1421856000000","110"),
);
$newData = json_encode($data);
echo $newData;
If you really need to display something similar to this:
[
[1421852400000, 100],
[1421856000000, 110],
[1421859600000, 125]
]
Change $data to something like this:
$data = array(
array(1421852400000, 100),
array(1421856000000, 110)
);
So i'm attempting to use highcharts with the pie chart drilldown option.
Working with static data this is working perfectly. However, as I would like to use the Pie chart as a form of reporting, Ideally It needs to run with dynamic data.
The top level data is made up of requests. Each request is made up of subsequent tasks.
This is the php I have which retrieves the tasks and requests.
foreach($getRequests as $key=> $val){
$timeArr = explode(':', $val['duration']);
$decTime = ($timeArr[0]) + ($timeArr[1]/60); // this is purely to convert hh:mm to decimal time
$pieData['name'] = $val['name'];
$pieData['y'] = $decTime;
$pieData['drilldown'] = $key;
$pie[]=$pieData;
// This creates the first level of data which the $pie[] array gives the correct format, so when json_encode is applied, the data is usable
$getTasks = $task->getReportTasks($user, $status, $key, $dateRange, $date);
foreach($getTasks as $taskKey => $taskVal){
$pieTasks['id']=$key;
$pieTasks['name'] = "Tasks";
$timeArrTask = explode(':', $taskVal['duration']);
$decTimeTask = ($timeArrTask[0]) + ($timeArrTask[1]/60);
$pieTasks['data'] = array($taskVal['name'], $decTimeTask);
$pie2[] = $pieTasks;
}
}
However by applying the same logic to tasks and using json_encode, I end up with the following.
[
{"id":25684
,"name":"Tasks"
,"data":["test task1",3]
}
,{"id":25684
,"name":"Tasks"
,"data":["testtask2",14.383333333333]
}
,{"id":25689
,"name":"Tasks"
,"data":["testtask3",1]}
]
But the format I need is for tasks with the same request ID, the "id" field to be contained within the same data field.
Like so
[
{"id":25684
,"name":"Tasks"
,"data":[
["test task1",3]
,["testtask2",14.383333333333]
]
}
,{"id":25689
,"name":"Tasks"
,"data":[
["testtask3",1]
]
}
]
where because testtask2 has the same id, it is contained within the same data field.
I hope this makes sense and any help anyone can provide so I can structure this correctly would be greatly appreciated.
Not tested, but try to replace the last foreach with this code:
$pieTasks['id'] = $key;
$pieTasks['name'] = "Tasks";
$pieTasks['data'] = array();
foreach($getTasks as $taskKey => $taskVal){
$timeArrTask = explode(':', $taskVal['duration']);
$decTimeTask = ($timeArrTask[0]) + ($timeArrTask[1]/60);
$pieTasks['data'][] = array($taskVal['name'], $decTimeTask);
}
$pie2[] = $pieTasks;
Standart JSON parser can't parse double (14.383333333333) .
Try write in double quotes ( "14.383333333333" )