I've created a chart and I want to update in real time, that's why I use ajax. My question is, how to display the ajax response? Below is my sample script of my chart. Please help me. Thank you very well.
Chart.php -
$(document).ready(function () {
Highcharts.chart('container', {
chart: {
type: 'bar'
},
title: {
text: "TITLE"
},
series: [{
name: 'Present',
data: [*//must display the ajax response here//*]
}]
});
});
ajax.php
<script>
function fanc_no(){
$.ajax({
url: "test.php",
success: function(result){
$("#container").html(result);
}
});
}
window.setInterval(function(){
func_no();
}, 1000);
</script>
Take a look at the load function:
chart: {
events: {
load: function () {
// set up the updating of the chart each second
var series = this.series[0];
setInterval(function () {
var x = (new Date()).getTime(), // current time
y = Math.round(Math.random() * 100);
series.addPoint([x, y], true, true);
}, 1000);
}
}
}
Now, inside the setInterval function, you have to call your ajax and pass the result as shown.
Take a look at the official docs for it.
Related
I m trying to figure it out that is it possible to make the json data fetched dynamically from a database with the help of php and mysql and can be plotted with highcharts that too dynamic auto updating? Any help would be appreciated.
following the code i have tried and is not working properly and want to implement to the the website for 10 lines.
<HTML>
<HEAD>
<TITLE>highchart example</TITLE>
<script type="text/javascript"src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<script type="text/javascript">
var chart;
function requestData() {
$.ajax({
url: 'live-server-data.php',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 20; // shift if the series is
// longer than 2
// add the point
chart.series[0].addPoint(point, true, shift);
// call it again after one second
setTimeout(requestData1, 1000);
},
cache: false,
});
}
function requestData1() {
$.ajax({
url: 'live-server-data.php',
success: function(point) {
var series2 = chart.series[1],
shift = series2.data.length > 20; // shift if the series is
// longer than 20
// add the point
chart.series[1].addPoint(point, true, shift);
// call it again after one second
setTimeout(requestData, 1000);
},
cache: false,
});
}
$(function () {
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
defaultSeriesType: 'spline',
events: {
load: requestData
}
},
title: {
text: 'Live random data'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis:
{
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: '',
margin: 80
}
},
series: [
{
name: 'Random data',
data: []
},
{
name: ' hahaha',
data: []
}
],
});
});
});
</script>
</HEAD>
<BODY>
<div id="container"
style="min-width: 728px; height: 400px; margin: 0 auto"></div>
</BODY>
</HTML>
*** the live-server-data.php is as followed:
<?php
// Set the JSON header
header("Content-type: text/json");
// The x value is the current JavaScript time, which is the Unix time multiplied
// by 1000.
$x = time() * 1000;
// The y value is a random number
$y = rand(48,52);
// Create a PHP array and echo it as JSON
$ret = array($x, $y);
echo json_encode($ret);
?>
You can try with
var options = {
chart: {
renderTo: 'chart',
},
credits: {
enabled: false
},
title: {
text: 'Impression/Click Overview',
x: -20
},
xAxis: {
categories: [{}]
},
tooltip: {
formatter: function() {
var s = '<b>'+ this.x +'</b>';
$.each(this.points, function(i, point) {
s += '<br/>'+point.series.name+': '+point.y;
});
return s;
},
shared: true
},
series: [{},{}]
};
$.ajax({
url: "json.php",
data: 'show=impression',
type:'post',
dataType: "json",
success: function(data){
options.xAxis.categories = data.categories;
options.series[0].name = 'Impression';
options.series[0].data = data.impression;
options.series[1].name = 'Click';
options.series[1].data = data.clicks;
var chart = new Highcharts.Chart(options);
}
});
The highcharts website has some useful articles about working with dynamic data. That is probably the best place to start.
http://www.highcharts.com/docs/working-with-data/preprocessing-live-data
http://www.highcharts.com/docs/working-with-data/preprocessing-data-from-a-database
Try something out, and if you have trouble, come back here with a more specific question showing what you have tried. As it stands, your question is too broad, and will probably get closed.
An ajax request for updating data looks something like:
function requestData() {
$.ajax({
url: 'live-server-data.php',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 20; // shift if the series is // longer than 20
// add the point
chart.series[0].addPoint(point, true, shift);
// call it again after one second
setTimeout(requestData, 1000);
},
cache: false
});
}
i have a php file which have a array like the following.
$selectShiftarray = array();
$shift=$_POST['selectShift'];
if ($shift)
{
foreach ($shift as $value)
{
array_push($selectShiftarray,$value);
}
}
i need to access the $selectShiftarray inside the AJAX to pass the value to another php file.
$.ajax({
type: 'POST',
url: '../c/sampleTest.php', //data: {data = <?php $POST['selectShift'] ?> },//"id=78&name=Allen",
dataType: 'json',
success: function (json) {
//alert('successful');
$.plot($("#placeholder"), json, {
series: {
stackpercent: true,
bars: {
show: true,
barWidth: 0.6,
align: "center"
}
},
xaxis: {
tickSize: 1
},
yaxis: {
max: 100,
tickFormatter: function (v, axis) {
return v.toFixed(axis.tickDecimals) + '%'
}
}
});
}
});
i tried to pass the array values in the data feild of the AJAX to sampleTest.php to perform calculation.
If i pass the array value directly between the two php files, i want to include the sampleTest.php inside the current php file. My requirement is, i should not include the sampleTest.php file inside any php file, hence i go for POST method of AJAX. But i can't able to pass array to the sampleTest.php file. Since i'm new to AJAX i can't solve this problem. can anyone help me to solve this problem.
Printing $selectShiftarray array into AJAX code to send it to ../c/sampleTest.php through AJAX:
function sendArrayToPHP(phpFile, parameterName, jsArray) {
$.ajax({
url: phpFile,
async: false, // Depending on what you want
type: "POST",
data: { parameterName : JSON.serialize(jsArray) }
}).done(function( data ) {
// Sent!
});
}
var arrayExample = $.parseJSON("<?=$selectShiftarray?>"); // This way
// You can modify here the array if you want using JavaScript
sendArrayToPHP("../c/sampleTest.php", "arrayParameter", arrayExample);
Receiving the array from ../c/sampleTest.php (decoding JSON):
$selectShiftArray = json_decode($_POST['arrayParameter'], true);
Thanks to axelbrz and Bergi for their Guidance which helped me to solve this problem , This Works for me,
Here is my AJAX code in Controller :
<script type="text/javascript">
$(document).ready(function(){
var jsonobj = <?php echo json_encode($selectShiftarray); ?>;
$.ajax({type:'POST',url:'../c/sampleTest.php', data : { shift : jsonobj } ,
dataType: 'json',
success:function(json){
//alert('successful');
$.plot($("#placeholder"), json, {
series: {
stackpercent: true,
bars: { show: true, barWidth: 0.6, align: "center" }
},
xaxis: {tickSize : 1},
yaxis:{max:100, tickFormatter: function(v,axis){ return v.toFixed(axis.tickDecimals)+'%'}}
});
}
});
});
</script>
<div id="placeholder" style="width:600px;height:300px; top: -401px; left: 500px;">
</div>
My sampleTest.php code, which receives the array send by controller and processing it.
$selectShiftarray = array();
$shift=$_POST['shift'];
if ($shift)
{
foreach ($shift as $value)
{
array_push($selectShiftarray,$value);
}
}
PROBLEM SOLVED
updated the jscrollpane to the latest version which support jquery 1.8 !
https://github.com/vitch/jScrollPane/blob/master/script/jquery.jscrollpane.min.js
I'm trying to refresh a div with content for a certain period. It will fire an Ajax GET call to a php script which render the content. For the first time ajax GET called, the ScrollPane is there, but for the second time Ajax GET(refresh) JScrollPane disappeared. Any how to reinitialize the jscrollpane?
function getActivity(callback)
{
$.ajax({
url: '../../views/main/activity.php',
type: 'GET',
complete: function(){
$('#activityLineHolder').jScrollPane({
verticalDragMinHeight: 12,
verticalDragMaxHeight: 12
//autoReinitialize = true
});
},
success: function(data) {
var api = $('#activityLineHolder').jScrollPane(
{
verticalDragMinHeight: 12,
verticalDragMaxHeight: 12
}
).data('jsp');
api.getContentPane().html(data);
api.reinitialise();
}
});
setTimeout(callback,10000);
}
$(document).ready(function(){
(function getActivitysTimeoutFunction(){
getActivity(getActivitysTimeoutFunction);
})();
});
Right now, my scrollpane is there after every Ajax call, but it shows buggy, the jscrollpane will keep moving left after every Ajax Call and slowly, it will hide the content. How is this happened?
foreach ($list as $notification) {
echo "<div class='feeds' id='$notification->notification_id'>";
$userObj = $user->show($notification->added_by);
echo $userObj->first_name.":<span class='text'>".$notification->activity."</span>";
echo " <span class='time'>".$notification_obj->nicetime($notification->created_at)."</span>";
echo "</div>";
}
something like this , that is my activity.php
here is my screenshot , anyone pls do help me #_#
http://img31.imageshack.us/img31/6871/jscrollpane.png
change the order of your commands. make a global variable that caches the ID like this:
var $activity, $activity_pane; // outside the dom ready
function getActivity(callback){
$.ajax({
url: '../../views/main/activity.php',
type: 'GET',
success: function(data) {
$activity_pane.html(data);
}
});
setTimeout(callback,10000);
}
$(function(){
$activity = $('#activityLineHolder');
$activity.jScrollPane({
verticalDragMinHeight: 12,
verticalDragMaxHeight: 12
autoReinitialise: true
});
$activity_pane = $activity.data('jsp').getContentPane();
(function getActivitysTimeoutFunction(){
getActivity(getActivitysTimeoutFunction);
})();
});
My understanding is that a callback should be executed when the code within your method completes. If you are then wanting to run the getActivity() method again, shouldn't that be used in setTimeout(). Something like this:
function getActivity(callback)
{
$.ajax({
url: '../../views/main/activity.php',
type: 'GET',
complete: function(){
$('#activityLineHolder').jScrollPane({
verticalDragMinHeight: 12,
verticalDragMaxHeight: 12
//autoReinitialize = true
});
},
success: function(data) {
$('#activityLineHolder').html(data);
}
});
setTimeout(function(){getActivity(callback);},10000);
if($.isFunction(callback)) {
callback();
}
}
I just take a look at http://jscrollpane.kelvinluck.com/ajax.html
I had tried and works. i change setTimeout into setInterval (function from scrollpane).
you can try this (i had tested)
$(document).ready(function(){
var api = $('#activityLineHolder').jScrollPane(
{
showArrows:true,
maintainPosition: false,
verticalDragMinHeight: 12,
verticalDragMaxHeight: 12,
autoReinitialise: true
}
).data('jsp');
setInterval(
function()
{
$.ajax({
url: '../../views/main/activity.php',
success: function(data) {
api.getContentPane().html(data);
}
});
},
10000
);
});
I've faced this problem before, here is a snippet so you can get the idea. Good luck!
attachScroll = function(){
return $('.scroll-pane').jScrollPane({
verticalDragMinHeight: 17,
verticalDragMaxHeight: 17,
showArrows: true,
maintainPosition: false
});
}; // in this var I store all settings related to jScrollPane
var api = attachScroll().data('jsp');
$ajaxObj = $.ajax({
type: "GET", //set get or post
url: YOUR_URL,
data: null,
cache: false, //make sure you get fresh data
async: false, //very important!
beforeSend: function(){
},
success: function(){
},
complete: function(){
}
}).responseText; //$ajaxObj get the data from Ajax and store it
api.getContentPane().html($ajaxObj); //insert $ajaxObj data into "api" pane previously defined.
api.reinitialise(); //redraw jScrollPane
You can define the ajax call as a function and put it into a setInterval.
An example from official docs can be found here
Hope it helps!
Well I suppose that your HTML content coming from AJAX is long and you have problem with decreasing area size because it takes some time to render content by .html():
api.getContentPane().html(data);
And when it goes to the next line api.reinitialise() - HTML rendering isn't complete yet, but jScrollPane already catches current DIV width / height, initializes by those width / height, and then remaining html content is being inserted - and it appears outside of jScrollPane boundaries.
Read similar question: Wait for jquery .html method to finish rendering
So my adice:
1) Add a DIV at the end of your PHP code which will mark end of HTML coming from Ajax:
foreach ($list as $notification) {
...
}
echo '<div id="end-of-ajax"></div>';
2) Add periodical (200ms) check for "end-of-ajax" in your JS code - when it finds the end is reached, it calls for api.reinitialise():
var timer = setInterval(function(){
if ($("#activityLineHolder").find('#end-of-ajax').length) {
api.reinitialise();
clearInterval(timer);
}
}, 200);
EDIT
This is full JavaScript code:
function getActivity()
{
$.ajax({
url: '../../views/main/activity.php',
type: 'GET',
complete: function(){
$('#activityLineHolder').jScrollPane({
verticalDragMinHeight: 12,
verticalDragMaxHeight: 12
//autoReinitialize = true
});
},
success: function(data) {
var api = $('#activityLineHolder').jScrollPane(
{verticalDragMinHeight: 12,verticalDragMaxHeight: 12}
).data('jsp');
api.getContentPane().html(data);
var timer = setInterval(function(){
if ($("#activityLineHolder").find('#end-of-ajax').length) {
api.reinitialise();
clearInterval(timer);
}
}, 200);
}
});
}
$(document).ready(function(){
setInterval(getActivity,10000);
});
Im not sure about what your content is but just make sure that you reset the widths and heights accordingly before reinitlizing. as i had the same issue, and that was the problem
var origHeight =$('#GnattChartContainerClip').height();
var GanttChart = $('#EntireGnattWrapper').get(0).GanttChart;
$('#GnattChartContainerClip').find('#PaddingGnatt').remove();
$('#HeadersCol').find('#PaddingHeaders').remove();
var pane = $('#GnattChartContainerClip');
$('#GnattChartContainerClip').height(origHeight+height);
$('#GnattChartContainerClip').append('<div id="PaddingGnatt" style="width:'+GanttChart.TotalWidth+'px;height:25px"></div>');
$('#HeadersCol').append('<div id="PaddingHeaders" class="header" style="height:25px"></div>');
var paned = pane.data('jsp');
paned.reinitialise();
I'm trying to create a chart using data from my database calling json, but its not showing the results in the chart.
Here's my code so far:
$(document).ready(function() {
function requestData() {
$.ajax({
url: 'data.php',
datatype: 'json',
success: function(data) {
alert(data);
chart.series[0].setData(data[0]);
},
cache: false
});
}
var chart;
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'line',
events: {
load: requestData
}
},
xAxis: {
},
yAxis: {
title: {
text: 'Value'
}
},
series: [{
name: 'Random data',
data: []
}]
});
});
And here's my data.php code
$query = "SELECT tiempo,Fp1Ref
FROM GraficaEEG limit 10";
$data = mysqli_query($dbc, $query);
$i=0;
while($row = mysqli_fetch_array($data)) {
$row['tiempo'] = (float) $row['tiempo'];
$rows[$i]=array($row['tiempo'],(float)$row['Fp1Ref']);
$i++;
}
echo json_encode($rows);
The data i receive is this:
[[0,3001],[0.005,4937.22],[0.01,4130.55],[0.015,4213.15],[0.02,4010.61],[0.025,3914.34],[0.03,3785.33],[0.035,3666.13],[0.04,3555.25],[0.045,3447.77]]
So i think is the proper way to pass data for the chart, so i don't quite get whats wrong, thank you in advance.
I think the problem is that when your requestData() function is fired the chart variable still isn't fully built and doesn't know it has the series property.
To fix this, instead of chart in your requestData() function, reference this (which means the chart object in that context).
I tried this out in jsfiddle here http://jsfiddle.net/elcabo/p2r6g/.
Also post the js code below.
$(function () {
$(document).ready(function() {
//Function bits
function requestData(event) {
var tiemposAlAzar = [[10,20],[20,50]];
//The 'this' will refer to the chart when fired
this.series[0].setData(tiemposAlAzar);
};
var chart;
//Chart bits
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'line',
events:{
load: requestData
}
},
xAxis: {},
yAxis: {
title: {
text: 'Value'
}
},
series: [{
name: 'Random data',
data: []
}]
});
});
});
This url may help you to create dynamic highchart that need to pull data from database.
In json.php code you can put your sql query and replace static array to dynamic array
http://www.kliptu.com/free-script/dynamic-highchart-example-with-jquery-php-json
The example also shows how to manage multiple series with json.
And tooltips with all series data at mouse point.
You can modify example as per your script requirement.
How can I use jQuery to constantly run a PHP script and get the response every second and also to send small bits of data on mouse down to the same script?
Do I really have to add some random extension just to get such a simple timer to work?
To iterate is human, to recurse divine.
-L. Peter Deutsch
var req = function () {
$.ajax({
url : 'http://example.com/yourscript.php',
complete : function () {
req();
}
});
};
req();
In case it's not obvious, the above will make a new request as soon as the previous one completes, forever. You could also set a 1 second delay between requests as follows:
var req = function () {
$.ajax({
url : 'http://example.com/yourscript.php',
complete : function () {
setTimeout(function () {
req();
}, 1000);
}
});
};
req();
function doAjax(data){
$.ajax({
type: "POST",
data: data,
url: 'http://example.com/yourscript.php',
});
}
// Set interval
setInterval('doAjax()',1000);
// Set event handler
$(document).mousedown(function(){
doAjax({key: 'value'});
});
You could replace $(document) with an actual element if you don't want to capture clicks on the whole page.
You can do a lot more with the ajax function if you are looking for callbacks etc:
http://docs.jquery.com/Ajax/jQuery.ajax
//All pings you need:
ping.pushCallback(function() { YourCallback(); });
$.data(document.body, 'data_ping', ping);
//------------------------------------------------------
//Script
$.ping = function(url, options) {
this.url = url;
this.options = $.extend({
delay: 2000,
dataType: 'json',
timeout: 10000,
data: {},
callbacks: []
}, options);
this.queue();
};
$.ping.prototype = {
queue: function() { var self = this;
setTimeout(function() {
self.send();
}, self.options.delay);
},
send: function() { var self = this;
$.ajax(self.url, {
success: function(data) {
for (var i in self.options.callbacks) {
self.options.callbacks[i](data);
}
},
complete: function() {
self.queue();
},
dataType: self.options.dataType,
data: self.options.data,
type: "GET",
cache: false,
timeout: self.options.timeout
});
},
setData: function(key, value) {
this.options.data[key] = value;
},
pushCallback: function(callback) {
this.options.callbacks.push(callback);
}
};
You can put the code for pinging the server in a function, then do something like this:
setInterval('ping()',1000); //this will ping 1000 milliseconds or 1 second
You don't have to add some random extension. There are native javascript functions setInterval and setTimeout for doing stuff on set intervals. You would probably want to do something like
function ajaxPing() {
...
}
setInterval("ajaxPing()", 1000);
$(element).mousedown(ajaxPing);
On the other hand, if you really want to do the pinging every second, it would probably be sufficient to just store your data in variables on mousedown and submit it on next ping (that will happen in less than a second).