The div is:
<div>
<canvas id="chart-area2" width="300" height="300"/>
</div>
how to refresh the above div every 10 seconds without reloading the page?
following is the javascript:
<script>
var pieData2 = [
{
value: <?= $pfstatetext;?>,
color:"#F7464A",
highlight: "#FF5A5E",
label: "Red :"
},
{
value: <?= $cpuusage; ?>,
color: "#46BFBD",
highlight: "#5AD3D1",
label: "Green"
},
{
value: 100,
color: "#FDB45C",
highlight: "#FFC870",
label: "Yellow"
},
{
value: 40,
color: "#949FB1",
highlight: "#A8B3C5",
label: "Grey"
},
{
value: 120,
color: "#4D5360",
highlight: "#616774",
label: "Dark Grey"
}
];
window.onload = function(){
var ctx2 = document.getElementById("chart-area2").getContext("2d");
var myPie2 = new Chart(ctx2).Pie(pieData2);
};
</script>
how can i use setInterval in the above code?.....................................................................................................
You may use that code
function refreshTheDiv(){
// Your drawing code here
window.setTimeout(refreshTheDiv,10000);
}
And replace the line // Your drawing code here with your code referencing the canvas element.
In your specific case :
(function(){
var myPie2;
window.onload = function(){
var ctx2 = document.getElementById("chart-area2").getContext("2d");
myPie2 = new Chart(ctx2).Pie(pieData2);
updateChart();
};
function updateChart()
{
$.getJson('/data.php',function(data){
// Do the update here (Seems dead : https://github.com/nnnick/Chart.js/issues/13 )
// You may deal with chartjs methods or recreate the chart:
myPie2 = new Chart(ctx2).Pie(data); // Quick and dirty solution
setTimeout(updateChart,10000);
});
}
})();
The data.php contains something like:
<?php
echo json_encode(
array(
array(
'value'=> $pfstatetext,
'color'=>"#F7464A",
'highlight'=> "#FF5A5E",
'label'=> "Red :"
),
array(
'value'=>$cpuusage,
'color'=> "#46BFBD",
'highlight'=> "#5AD3D1",
'label'=> "Green"
),
array(
value: 100,
color: "#FDB45C",
highlight: "#FFC870",
label: "Yellow"
)
//...
)
);
You must include JQuery : http://code.jquery.com/jquery-1.11.1.js
for my solution to work
ChartJS update data
If you want to update the canvas painting and you're not working with the server, use js setTimeout or setInterval (You can read about these functions here: http://www.w3schools.com/js/js_timing.asp). In the callback function that you pass to these functions you work with the canvas' context object and paint whatever you want.
If you want to update the content, like text and HTML, or if the painting is related to the server, I think you should use AJAX. AJAX enables communication after the page was loaded, so you don't have to load the whole page again. There are many tutorials for ajax, one of them is on W3schools. Also, if you work with AJAX, you should use the timing functions that I've mentioned before in order to refresh it every 10 seconds.
Another solution is to use Server-Sent Events. If you want to refresh the div in order to UPDATE the content (according to the DB, the server, etc.) so the content will be always updated, you can use this technique that follows about differences and updates, and loads them. You can read about it here : http://www.w3schools.com/html/html5_serversentevents.asp. I'm not sure if this technique is what you're looking for, it depends on what is your purpose of reloading the page, so I think the AJAX would be a great solution if the content is from the server, and the first solution is the only one which is correct if you don't work with the server.
write one function to fetch content inside div trough ajax, and write a jquery code to call the function in every 10 seconds.
For example:
function fetch_content(){
$.ajax({
url: "url for ajax page",
type: "POST",
success: function(data){
$('div').html();
}
});
}
and code to call this function every 10 seconds
setInterval(fetch_content,10000);
Related
This is my page code and when I click on button work just first time:
I saw question about but I couldn't solve my problem!
<html>
<head>
<title>tsee</title>
<script src="jquery.js" type="text/javascript"></script>
<script>
$(document).ready(function () {
$("#btn").click(function () {
$.ajax({
URL: "../../generate", //this read from a servlet
type: "get",
data:{
id:120
},
cache: false,
complete: function () { alert('farshid') },
success: function (data) {
$('#result').html(data);
},
error: function () {
alert('Error')
}
})
})
});
</script>
</head>
<body>
<input type="button" id="btn" value="Ajax Request" />
<div id="result">
</div>
</body>
</html>
When I click on button, my result load to div(Draw a chart in this div and Because avoid from huge code I avoid to write here) and in second time when I click on don't work.
How can I solve this problem?
And this is video for better understanding problem.(video from my run enviroment
I think you can try .on('click', function(){ // your code }) instead of simple .click function.
After looking at your video and the jsfiddle, the problem has nothing to do with the button.
If you had opened the console, you would have seen that the problem occurs when setting the options for the HighCharts plugin.
You try to change the colors from flat to gradients, but you run this code each time you try to draw a chart.
This code assumes that the initial colors are hex values but the second time you run it it is not hex (since you changed them on the first run), and this causes the plugin to crash and stop executing (and thus it never reaches the part that draws the chart)
See problematic demo: http://jsfiddle.net/dgr2ky4h/
You need to remove the HighChart color setting from that function and only run it once when you load the page.
See working demo: http://jsfiddle.net/dgr2ky4h/1/
So remove the following code from your success method
Highcharts.getOptions().colors = Highcharts.map(
Highcharts.getOptions().colors,
function (color) {
console.log(color);
return {
radialGradient: {
cx: 0.5,
cy: 0.3,
r: 0.7
},
stops: [
[0, color],
[
1,
Highcharts.Color(color)
.brighten(-0.3)
.get('rgb')] // darken
]
};
and run it out of the success only once..
<script>
$(function(){
Highcharts.getOptions().colors = Highcharts.map(
Highcharts.getOptions().colors,
function (color) {
console.log(color);
return {
radialGradient: {
cx: 0.5,
cy: 0.3,
r: 0.7
},
stops: [
[0, color],
[1, Highcharts.Color(color)
.brighten(-0.3)
.get('rgb')] // darken
]
};
});
});
</script>
could be a binding issue...
.click binds event to button as many times as you click. try
Either using $("element").on("click", function(){do stuff here});
or unbind click on button after you execute stuff...
wrong answer...Apologies
I want to do autocomplete for textarea using entered values from browser. It is working for Textbox but not working Text area.
Normal textbox indeed get autocomplete behaviour for free.
As far as i know, you can get similar behaviour for textarea (even better, with all history) with installing lazarus plugin in your web browser.
Once installed, you will get a small cross icon on the top right corner. Clicking it will popup previous entries.
I usually don't like to install third party plugin in my web browser but this can save a lot of time and frustration when accidentally loosing all the text we already type.
First you need to include jquery UI then use the example code
HTML
<div class="ui-widget">
<label for="tags">Tags:</label>
<textarea id="tags" size="30"></textarea>
</div>
JS
$(function () {
$("document").ready(function () {
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"];
$("#tags").on("keydown", function () {
var newY = $(this).textareaHelper('caretPos').top + (parseInt($(this).css('font-size'), 10) * 1.5);
var newX = $(this).textareaHelper('caretPos').left;
var posString = "left+" + newX + "px top+" + newY + "px";
$(this).autocomplete("option", "position", {
my: "left top",
at: posString
});
});
$("#tags ").autocomplete({
source: availableTags
});
});
});
You Need to use external plugin
Scripts and CSS
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
HTML
<textarea id="demo"></textarea>
Script
<script>
$(function() {
//Get the Data from a JSON or Hidden Feild
var availableTags = ["jQuery.com", "jQueryUI.com", "jQueryMobile.com", "jQueryScript.net", "jQuery", "Free jQuery Plugins"]; // array of autocomplete words
var minWordLength = 2;
function split(val) {
return val.split(' ');
}
function extractLast(term) {
return split(term).pop();
}
$("#demo") // jQuery Selector
// don't navigate away from the field on tab when selecting an item
.bind("keydown", function(event) {
if (event.keyCode === $.ui.keyCode.TAB && $(this).data("ui-autocomplete").menu.active) {
event.preventDefault();
}
}).autocomplete({
minLength: minWordLength,
source: function(request, response) {
// delegate back to autocomplete, but extract the last term
var term = extractLast(request.term);
if(term.length >= minWordLength){
response($.ui.autocomplete.filter( availableTags, term ));
}
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function(event, ui) {
var terms = split(this.value);
// remove the current input
terms.pop();
// add the selected item
terms.push(ui.item.value);
// add placeholder to get the comma-and-space at the end
terms.push("");
this.value = terms.join(" ");
return false;
}
});
});
</script>
DEMO LINK
ANOTHER PLUGIN TEXTEXTJS
Browsers do not currently support autocompletion for a textarea. The autocomplete attribute is formally allowed for textarea in HTML5 and it has the default value of on, but this value just means that browsers are allowed to use autocompletion. They do not actually use it for textareas, apparently because it would seldom be useful and could actually be confusing. It is much more probably that a user wants to reuse his address information, entered in single-line text input fields, than some longish text he has entered in, say, a feedback form of some site and now some other site happens to have a comments textarea with the same name.
Thus, all you can do is to set up some autocomplete functionality of your own. (This is what other answers suggest in various ways.) This means that you need to store user input somehow (which is what browsers do for their own autocompletion operations too), e.g. in cookies or in localStorage. This generally means that the functionality works inside a site, on pages using the same technique to implement it, but not across sites.
how can I display data point on bar in barchart?
I don't want to use datatip or tooltip which will highlight data points only when they are moused over.
I want to display the data point always on the bar.
is there any right way to get it?
thanks.
I want exactly like this
following is my code
<p:barChart id="barChartId" value="#{myBean.myModel}"
orientation="horizontal"
stacked="true" extender="ext" animate="true" shadow="false" />
<h:outputScript>
function ext() {
this.cfg.highlighter = {
useAxesFormatters: false,
tooltipAxes: 'x'
};
this.cfg.legend = {
show: true,
location: 'ne',
placement: 'outside'
};
this.cfg.seriesDefaults = {
pointLabels : { show: true },
};
}
</h:outputScript>
here, highlighter and legend are working fine but point labels are not displaying on bar
Not sure if it will work...
Use the extender of the <p:barChart , like this:
<p:barChart value="#{myBean.myModel}" widgetVar="myBarChart" extender="my_ext"/>
<script type="text/javascript">
function my_ext() {
this.cfg.seriesDefaults = {
renderer:$.jqplot.BarRenderer,
pointLabels: {show: true}
};
this.cfg.stackSeries: true;
}
</script>
or this
<script type="text/javascript">
function my_ext() {
this.cfg.seriesDefaults = {
pointLabels: {show: true}
};
this.cfg.stackSeries: true;
}
</script>
Also take a look at the jqplot examples : Bar charts
Just in case someone doesn't crawl through the comments of the marked answer, as I didn't do in the first place.
The problem basically is not the configuration of the pointLabelselement, but rather that primefaces (as of 4.0) in its original state does not ship with the needed plugin of jqPlot included.
Therefore actually the solution is to make the needed plugin jqplot.pointLabels.min.js available. From a ticket in the bug tracker (http://code.google.com/p/primefaces/issues/detail?id=5378) I extracted, that primefaces uses jqPlot version 1.0.8.
download jqplot 1.0.8 from https://bitbucket.org/cleonello/jqplot/downloads/
add the plugin to your project (e.g. src/main/webapp/resources/jqplot-plugins)
add the plugin as script to your page (<h:outputScript library="jqplot-plugins" name="jqplot.pointLabels.min.js" />)
Just getting started with Backbone and still making sense of the ins and outs.
I'm trying to simply display some JSON using Underscore and Backbone. I'm able to make it to work just using Underscore and $.getJSON, but when I try to wire it up with Backbone I get a variety of errors depending upon what I try.
I've also been able to get Backbone to work by hardcoding values in to the model, but I'm running in to a wall when I try to bring it all together. Any help is appreciated.
Here is my Underscore template:
<script type="text/html" id='trailTemplate'>
<% _.each(trails,function(trail){ %>
<%= trail.trailname %><br />
<% }); %>
</script>
And here is my Backbone code:
var Trail = Backbone.Model.extend({
urlRoot: "trails.json"
});
var trail = new Trail({});
var TrailView = Backbone.View.extend({
el: '.page',
template: _.template($("#trailTemplate").html(), {trails:trail.fetch()}),
render: function(){
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});
var trailView = new TrailView({
model: trail
});
trailView.render();
And in case you need it, here is trails.json
[
{
"trailhead": "Bear Lake",
"trailname": "Bear Lake",
"distance": ".5",
"gain": "20",
"level": "easy"
},
{
"trailhead": "Bear Lake",
"trailname": "Nymph Lake",
"distance": ".5",
"gain": "225",
"level": "fairly easy"
}
]
Your trails.json file contains an array with 2 objects, which both represent a single 'Trail'. So you should have a collection 'Trails' instead of a single model
var Trails = Backbone.Collection.extend({
url: '/trails.json'
});
var trails = new Trails();
The underscore template function can be used in 2 ways:
_.template(templateString) - compiles the templateString into function that can be evaluated when necessary
_.template(templateString, data) - compiles and immediately evaluates the template with the given data
Now the way you are using is number 2 (the way you declare the template) combined with number 1 (how you use it inside render). Let's examine the template declaration:
template: _.template($("#trailTemplate").html(), {trails:trail.fetch()})
This is all good up until the point you try to give it the data -attribute. First of all you don't need to give the data at this point, you just want to create the template function that can be evaluated when the View renders. Second, the stuff you are trying to pass as data is not at all what you think it is.
trail.fetch() doesn't return the the fetch results, it returns the ajax handle for the ajax call that is made with fetch. Thankfully Backbone is made so you don't have to think about all this painful ajax stuff, but instead you can trust the events that Backbone emits. So whip out the Backbone Catalog o' Events and check out reset
"reset" (collection, options) — when the collection's entire contents have been replaced.
This is the event you collection will emit, after fetch (also sync, i think). Before this event is emitted, your collection will be empty, so there is no point in doing anything with it before hearing this reset event. So let's bring it all together now:
var TrailView = Backbone.View.extend({
el: '.page',
template: _.template($("#trailTemplate").html()), // no data attribute here
initialize: function() {
this.collection.on('reset', this.render); // render after collection is reset
this.collection.fetch(); // fetch the collection from the trails.json file
}
render: function(){
// evaluate the template here
this.$el.html(this.template(this.collection.toJSON()));
return this;
}
});
var trailView = new TrailView({
collection: trails
});
// trailView.render(); <- No need for this, because it will render itself
Hope this helps!
I'm using tablesorter and tablesorter.pager. Here is my code:
$(document).ready(function() {
$("#peopletable")
.tablesorter({ widthFixed: true, widgets: ['zebra'] })
.tablesorterFilter({ filterContainer: $("#people-filter-box"),
filterClearContainer: $("#people-filter-clear-button"),
filterColumns: [1, 2, 3],
filterCaseSensitive: false
})
.tablesorterPager({ container: $("#peoplepager") });
$("#peopletable tr.data").click(function() {
var personid = $(this).attr('id');
$.ajax({
type: "POST",
url: "/Search/GetDocumentsByPerson",
data: { "id": personid },
datatype: "json",
success: function(data) {
var results = eval(data);
$("#documentstable > tbody tr").remove();
$.each(results, function(key, item) {
$("#documentstable > tbody:last").append(html);
});
$("#documentstable").trigger("update");
}
});
});
});
Everything works great except when I click on the next page my button click event doesn't fire. Is this a known issue with jQuery tablesorter?
It's because the elements are updated, the ones you bound the click handler to are gone, you can use .live() to resolve this, change this:
$("#peopletable tr.data").click(function() {
To this:
$("#peopletable tr.data").live('click', function() {
Alternatively, if #peopletable isn't destroyed you can use .delegate(), like this:
$("#peopletable").delegate('tr.data', 'click', function() {
I have also faced the same kind of problem with tablesorterPager second page after using Jeditable (edit in place) plugin for some element in the tablesorterPager used table.
I have tried editing the data bind function in Jeditable as follows
original code
$(this).bind(settings.event, function(e) {
here settings.event equals to the event parameter which we are defining with options eg: click
modified code
$(this).live(settings.event, function(e) {
But.. I found the error with tablesorterPager within pages other than the first page is not because of the binding of element event.
when we are calling tablesorterPager to any table with many rows, only the first page rows of
the table is affected on the page load. so only the first page rows are called with Jeditable plugin. other rows in the other pages are not assigned with the plugin. because of this reason, the events in other pages than first page will not work.
to prevent above situation, we can add Jeditable plugin calling inside updatePageDisplay function.
eg:
function updatePageDisplay(c) {
$(".tablerowdata").each(function(){
$(this).editable("ajax/save.php", {
tooltip : "click to edit...",
data : {"selectid1":"selectval1","selectid2":"selectval2","selectid3":"selectval3"},
type : "select",
submit : "ok",
event : "click",
select : "true",
});
});
Creating a new element won't duplicate the event created with the click method wheras the live method does it.