I would like to use jqPlot usinge data from server side coming in JSON, like described in this example: http://www.jqplot.com/tests/data-renderers.php
My code is nearly the same like the example:
function myGraph(jsonurl) {
var ajaxDataRenderer = function(url, plot, options) {
var ret = null;
$.ajax({
// have to use synchronous here, else the function
// will return before the data is fetched
async: false,
url: url,
dataType:"json",
success: function(data) {
ret=data;
console.warn(data);
}
});
return ret;
};
var plot1 = $.jqplot('chartdiv', jsonurl, {
title: 'myTitle',
dataRenderer: ajaxDataRenderer,
dataRendererOptions: { unusedOptionalUrl: jsonurl },
series: [{
label: 'myLabel',
neighborThreshold: -1
}],
axes: {
xaxis: {
renderer: $.jqplot.DateAxisRenderer,
// min:'August 1, 2010 16:00:00',
tickInterval: '2 months',
tickOptions:{formatString:'%Y-%m-%d.%H:%M:%S'}
},
yaxis: {
tickOptions:{formatString:'$%.2f'}
}
},
});
On server side i'm using PHP (and Yii). The webpage returns an array, which is encoded to JSON by using CJSON::encode($resultArray); (this Yii function passed trough to the PHP JSON encode function).
The Results from the PHP script lookes like that:
{"2011-04-25 14:46:40":2,"2011-04-26 14:46:40":3,"2011-04-27 14:46:40":5}
The Ajax request on client side resolved something like this (output from console.info(); )
Object { 2011-04-25 14:46:40=2, 2011-04-26 14:46:40=3, ...}
Probably, jqPlot expect the following format:
[[["2011-04-25 14:46:40":0],["2011-04-26 14:46:40",3],["2011-04-27 14:46:40",0]]]
All the time i get the error uncaught exception: [object Object]
What is wrong?
Is there a way to convert the object for to the typical array form?
Thank you
I have something like this . I had 2 arrays for values,labels .You should construct string as below from arrays .
$size = count($labels);
for ($i = 0; $i < $size; $i++) {
$result = $result . "['" . $labels[$i] . "'," . $values[$i] . "]";
if($i != $size -1 ){
$result = $result . ",";
}
}
OR if you dont have 2 arrays and just have this string {"2011-04-25 14:46:40":2,"2011-04-26 14:46:40":3,"2011-04-27 14:46:40":5} you can replace { with [ , } with ] and , with ],[ . A dirty but quick solution .
After above code you might need to append '[' and ']' on both sides and return value.
Do not parse the result on the client side, jquery will do much better. Actually, the array you need for jqplot is in fact valid json. All you have to do is prepare your data and create the appropriate array structure in PHP:
$pairs = array(1=>2, 3=>5, 4=>7, 5=>12, 7=>23); // simple example
$result = array();
foreach ($pairs as $label => $value) {
$result[] = array($label,$value); // make a "small" array for each pair
}
echo json_encode(array($result)); // wrap the result into another array; multiple plot data go like "array($result, $result2, ...)"
The result looks like this:
[[[1,2],[3,5],[4,7],[5,12],[7,23]]]
and is excatly what you need.
From http://www.jqplot.com/tests/date-axes.php
Note, although jqPlot will parse most any human readable date, it is safest to use javascript time stamps when possible. Also, it is best to specify a date and time and not just a date alone. This is due to inconsistent browser handling of local time vs. UTC with bare dates.
And example data from site:
var line1=[['2008-09-30 4:00PM',4], ['2008-10-30 4:00PM',6.5], ['2008-11-30 4:00PM',5.7], ['2008-12-30 4:00PM',9], ['2009-01-30 4:00PM',8.2]];
So you need array filled with 2 element arrays. First string with date (use timestamp if can) and X value. I've tried to find input format for datetime parsing or something like that but with no result.
You generated
{"2011-04-25 14:46:40":2,"2011-04-26 14:46:40":3,"2011-04-27 14:46:40":5}
which is object with 3 fields. First field name is "2011-04-25 14:46:40" and it's value set to 2. You need to generate array like this:
[["2011-04-25 14:46:40", 0],["2011-04-26 14:46:40", 3],["2011-04-27 14:46:40", 0]]
JSFiddle with your data seems to work - so don't need timestamps ;)
http://jsfiddle.net/zpygcvps/1/
sine curve with PHP json_encode function
server side
<?php
$y = array();
$index = 0 ;
for($x = 0 ; $x< 13 ; $x += 0.5) {
$y[$index] = sin($x);
$index++ ;
}
$series = array();
$series[0] = $y ;
$data = json_encode($series);
echo $data;
?>
client side
<script type="text/javascript">
$(document).ready(function(){
var ajaxDataRenderer = function(url, plot, options) {
var ret = null;
$.ajax({
async: false,
url: url,
dataType:"json",
success: function(data) {
ret = data;
}
});
return ret;
};
// The url for our json data
var jsonurl = "/test/chart/jqplot-data.php";
var plot2 = $.jqplot('chartdiv', jsonurl,{
title: "AJAX JSON Data Renderer",
dataRenderer: ajaxDataRenderer,
dataRendererOptions: {
unusedOptionalUrl: jsonurl
}
});
});
</script>
Related
I have a JSON array being passed form PHP and it looks like this:
[{from: "2019,09,14", to: "2019,09,14"}]
and I need it to look like this:
[{from: [2019, 9, 14], to: [2019, 9, 17]}]
here is my code thus far:
function getPricingDateRanges() {
var city = document.getElementById("pricingcityselect").value;
$.ajax({
url: 'getpricingdaterangepicker.php?city=' + city, // Change this to the uri of your file
method: 'GET', // Use the GET method
dataType: 'json', // Expect a JSON response
success: function(response) { // What will happen when the request succeeds
var darray = [{from:[2019,9,14], to:[2019,9,17]}];
console.log(response);
console.log(darray);
}
});
}
Added code from my PHP:
<?php
include 'dbconfig.php';
$city = ($_GET['city']);
$sql="SELECT start_date, end_date FROM date_ranges WHERE city='" . $city . "'";
$result = mysqli_query($conn,$sql);
// Create empty array.
$date_ranges = array();
// Add every row to array;
while($row = mysqli_fetch_array($result)) {
// Create an associative array to store the values in.
// This will later be a JavaScript Object.
$from = new DateTime($row['start_date']);
$ffrom = $from->format('Y,m,d');
$to = new DateTime($row['end_date']);
$fto = $from->format('Y,m,d');
array_push($date_ranges, array(
'from' => $ffrom,
'to' => $fto
));
}
// Send the $date_ranges as JSON.
$json = json_encode($date_ranges); // '[{"start": "2019-08-18", "end": "2019-08-19"}]'
echo $json;
?>
First, it's important to point out that the "JSON" you've included is not JSON. It is neither a string, nor are the property names quoted.
However, if this is actually the input you're dealing with, you can loop through the items, split the from and to values on ,, and use .map(Number) to convert them to integers.
const arr = [{from: "2019,09,14", to: "2019,09,14"}];
//Helper function to split on comma, convert items to numbers
const toIntegerArray = str => str.split(",").map(Number);
const result = arr.map(({from,to}) => ({
from: toIntegerArray(from),
to: toIntegerArray(to)
}));
console.log(result);
Parse JSON till the point with "2019,09,14".
then "2019,09,14" convert to array of numbers by:
"2019,09,14".split(',').map(el => parseInt(el, 10))
I'm working with JavaScript and PHP using arrays, the first step is create the array, here
var ListaA=[];
var i = 0, len = options.length;
while (i < len){
var tmp = {
'proyecto':'test',
'pendientes1':0,
'pendientes2':0,
'terminadas1':0,
'terminadas2':0,
'solucion':0
};
ListaA.push(tmp);
i++;
}
Then i send it to my PHP file like this
var laLista = JSON.stringify(ListaA);
$.get("php/operation.php?test="+ {'test' : laLista }, function( data ){
var tmp = {
'proyecto':""+value['proyecto']+"",
'pendientes1':""+value['pendientes1']+"",
'pendientes2':""+value['pendientes2']+"",
'terminadas1':""+value['terminadas1']+"",
'terminadas2':""+value['terminadas2']+"",
'solucion':""+value['solucion']+""
};
ListaA.push(tmp);
});
As you can see above i have ready the code to get the data which represents the array sent by the PHP file, so i got covered that part, my issue here is in my PHP file, here.
$arrayWork = json_decode($_POST['test']);
Then i want to loop, this time, just for testing i'm just taking one of the values and incresing it to watch the result, like this
foreach($arrayWork as $value){
$value['pendientes1']++; // this is not working for me
}
I got the following: "invalid argument supplied in foreach". So, what's wrong with my code? and which is the properly way to loop it and return it to my JavaScript?
I hope you can help me out with this issue. Thank you for your time and attention, good night.
Using this code
$arrayWork = json_decode($_POST['test']);
your json isn't really converted into an associated array, look at below
mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )
assoc
When TRUE, returned objects will be converted into associative arrays.
To convert json object into an array just add true to the second parameter to it
$arrayWork = json_decode($_POST['test'], true);**strong text**
To increment an index value in an array
foreach($arrayWork $key => as $value){
$arrayWork['pendientes1']++;
}
Edited.
also since you are using $_POST method change your ajax from $.get to $.post
$.post("php/operation.php?test="+ {'test' : laLista }, function( data ){
var result = JSON.parse(data); // parse json string into json object
...
});
If you want to read $_POST, you have to make a POST request:
$.ajax({
url:'php/operation.php',
type:"POST",
data: { test: ListaA },
contentType:"application/json; charset=utf-8",
dataType:"json",
success: function(){
...
}
})
You can't use $.post, because you have to set the contentType to JSON.
Important: you don't need to run JSON.stringifyyourself, jQuery will take care of it for you - so pass the original ListaA array.
What I am trying to do doesn't feel difficult, but for some reason I can't seem to find the correct way to ouput this JSON array, from php.
PHP code:
$a = array();
$i=0;
while($row = mysqli_fetch_array($result))
{
$i++;
$a = array();
$epoch = $row['time'];
$dt = new DateTime("#$epoch"); // convert UNIX timestamp to PHP DateTime
$a = array(
"time" => $dt->format('Y-m-d H:i:s'),
"signal" => $row['signal'],
"symbol" => $row['symbol'],
"price" => $row['price'],
"timeframe" => $row['timeframe'],
"epoch" => $row['time']);
echo json_encode($a, JSON_UNESCAPED_SLASHES);
}
Output:
{
"time":"2016-11-14 17:23:00",
"signal":"Sell",
"symbol":"XAUUSDecn",
"price":"1221.64000",
"timeframe":"M1",
"epoch":"1479144180"
}
{
"time":"2016-11-14 17:07:59",
"signal":"Sell",
"symbol":"GBPJPYecn",
"price":"135.13200",
"timeframe":"M1",
"epoch":"1479143279"
}
The correct output should have },{ NOT }{ between each object.
What I am ultimately trying to do:
function getTrades(a) {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "core/engine.php",
data: "q=data&account="+a,
dataType: "html", //expect html to be returned
success: function(response){
if(response=="nologin") {
alert("Sorry, but either your account is not activated or your login is incorrect!");
} else {
var j = $.parseJSON(response);
$.each(j, function (k, v) {
$("#trades").html('<span class="tradesignal"><!-- span class="signalarrowup"></span-->'+v.time+'<span style="color:#2DC14E;"> '+v.signal+'</span> <button class="tsym" id="sym_'+v.epoch+'">'+v.symbol+'</button> '+v.price+' '+v.timeframe+'</span>');
});
}
//alert(response);
console.log(response);
}
});
}
Each {json},{json} object will have its data printed into a span on an html page.
Appreciate the guidance!
Try creating a results array and push each one of the objects there, then after the loop finishes, convert the array to json and print it.
example:
$results = array();
$i = 0;
while($row = mysqli_fetch_array($result)){
//your code here
$a = array("time" => ....);
$results[] = $a; //this will add $a to $results
}
echo json_encode($results, JSON_UNESCAPED_SLASHES);
Just to add a little more explanation in addition to the code the other answers are suggesting. The problem is, you aren't outputting a JSON array. Each time you do
echo json_encode($a, JSON_UNESCAPED_SLASHES);
inside your loop, you output a valid JSON object like:
{
"time":"2016-11-14 17:23:00",
"signal":"Sell",
"symbol":"XAUUSDecn",
"price":"1221.64000",
"timeframe":"M1",
"epoch":"1479144180"
}
However, when you output the subsequent objects, getting a result like
{
"time": ...
}
{
"time": ...
}
You no longer have valid JSON. Even though each of the individual objects is valid, concatenating them together isn't. Simply adding a comma between the objects will still not make it valid. In order to produce an actual JSON array, the comma separated objects will need to be enclosed in square brackets like this:
[
{
"time": ...
},
{
"time": ...
}
]
That's why you need to add each of the arrays you're creating in the loop to an outer array and then json_encode the whole thing after the loop. The outer PHP array will become the outer JSON array you need.
As Xorifelse said, you want to put the data in an array, and then call json_encode on the array. Here is a code that should work:
$a = array();
$i=0;
while($row = mysqli_fetch_array($result))
{
$i++;
$epoch = $row['time'];
$dt = new DateTime("#$epoch"); // convert UNIX timestamp to PHP Date
$a[] = array("time" => $dt->format('Y-m-d H:i:s'), "signal" => $row['signal'], "symbol" => $row['symbol'], "price" => $row['price'], "timeframe" => $row['timeframe'],"epoch" => $row['time']);
}
echo json_encode($a, JSON_UNESCAPED_SLASHES);
I am echoing two array values from PHP. How do I differentiate these values in ajax.
if(#mysql_select_db("trainer_registration"))
{
$select_query_num = #mysql_query("select program_id,facilitator_id,availability_status from program_facilitator");
$select_query_name = #mysql_query("select facilitator_id,firstname,lastname,email_id from facilitator_details");
$num_rows = #mysql_num_rows($select_query_num);
$trainerdetails = [];
$traineravaildetails = [];
$i = 0;
while($row = #mysql_fetch_assoc($select_query_num))
{
$trainerdetails[$i]['pgidi'] = $row['program_id'];
$trainerdetails[$i]['facilitatorid'] = $row['facilitator_id'];
$trainerdetails[$i]['avail_status'] = $row['availability_status'];
$trainerdetails[$i]['idi'] = $row['facilitator_id'];
$i++;
}
while($row1 =#mysql_fetch_assoc($select_query_name))
{
$traineravaildetails[$i]['facilitatorid'] = $row1['facilitator_id'];
$traineravaildetails[$i]['firstname'] = $row1['firstname'];
$traineravaildetails[$i]['lastname'] = $row1['lastname'];
$traineravaildetails[$i]['emailidvalue'] = $row1['email_id'];
$i++;
}
echo json_encode($trainerdetails);
echo json_encode($traineravaildetails);
}
?>
function loadavailabletrainers (m) {
$.ajax({
url: 'assignavailtrainers.php',
data: { action:'test' },
type: 'post',
success: function(output) {
console.log(output);
}
});
}
I've seen a examples of multiple return values from php and handling them in ajax, but I didn't understand them. Can someone please explain how to differentiate output values in my case?
OUTPUT:
[[{"pgidi":"3","facilitatorid":"2","avail_status":"1","idi":"2"},{"pgidi":"3","facilitatorid":"1","avail_status":"2","idi":"1"},{"pgidi":"3","facilitatorid":"2","avail_status":"1","idi":"2"},{"pgidi":"3","facilitatorid":"1","avail_status":"2","idi":"1"},{"pgidi":"3","facilitatorid":"2","avail_status":"1","idi":"2"},{"pgidi":"3","facilitatorid":"2","avail_status":"1","idi":"2"},{"pgidi":"3","facilitatorid":"2","avail_status":"2","idi":"2"}],{"7":{"facilitatorid":"1","firstname":"Vignesh","lastname":"Anand","emailidvalue":"v*******#gmail.com"},"8":{"facilitatorid":"2","firstname":"Vignesh","lastname":"Anandakumar","emailidvalue":"vign*****#gmail.com"},"9":{"facilitatorid":"3","firstname":"Vignesh","lastname":"Anand","emailidvalue":"v*****#hotmail.com"},"10":{"facilitatorid":"4","firstname":"Vignesh","lastname":"Anand","emailidvalue":"****#live.com"}}]
It's a nice practice to send only one stream of values so you can process it all at once.
First, you could create a container array:
$data = array('trainerdetails' => $trainerdetails,
'traineravaildetails' => $traineravaildetails);
Then
echo json_enconde($data);
This will generate a merged output.
The encoded string returned by your PHP code needs to be decoded in the client side (more details: Parse JSON in JavaScript?). Because of that, you could use $.getJSON(), which is an alias for a specific call to $.ajax (doc: http://api.jquery.com/jquery.getjson/).
The 'success' function will pass a 'key'=>'value' array data. In this case you'd need to treat the value as they may contain extra levels of arrays. It helps if you can visualize your data structure as tree view, like this: http://jsonviewer.stack.hu/ (paste your output there).
I hope it helps!
In page load I am calling this function
function myFunction(selectedCinemaID) {
$.ajax({
type: "POST",
url: "show_details.php",
data: {cinema_id: selectedCinemaID }
}).done(function( show_list ) {
console.log(show_list.length);
});
And my code in show_details.php
$query = "SELECT * FROM `show` WHERE cinema_id=2;";
$result = mysql_query($query);
if($result){
$show_list = array();
while($row = mysql_fetch_array($result)){
array_push ($show_list, array($row['id'], $row['cinema_id'], row['show_time']));
}
echo json_encode($show_list);
} else {
echo mysql_error();
}
In my database I have only two row and three column but the length showed in the console is 64. But according to the database length should be 2. console.log(show_list) output [["2","2","2014-11-01 01:00:00"],["3","2","2014-11-01 04:00:00"]] but it seems everything here is treated as an array element or string. What is wrong in this code?
You haven't told jquery that you're sending JSON. As such, it'll treat the json text that the server is sending as text. That means
console.log(show_list.length);
is outputting the length of the json string, not the count/size of the array you're building in PHP.
You need either
$.getJSON(....);
or
$.ajax(
dataType: 'json'
...
)
However, note that if your mysql query fails for any reason, then outputting the mysql error message as your are will cause an error in jquery - it'll be expecting JSON, and you could potentially be sending it a mysql error message, which is definitely NOT json.
Once you switch to JSON mode, you should never send anything OTHER than json:
if (query ...)
output json results
} else {
echo json_encode(array('error' => mysql_error()));
}
The JavaScript function .length is counting the length of the entire serialized array string. You need to parse it first:
.done(function( show_list ) {
var data = JSON && JSON.parse( show_list ) || $.parseJSON( show_list );
console.log( data.length );
});
Thanks,
Andrew