I have a Javascript Gage that displays a percent and refreshed every 5 seconds in an ASPX page. As of now I am refreshing the whole page. How can I refresh just the Javascript Gage? Refreshing the whole page is not good practice. The Gage is inside div gg11. I am new at javascript, how can I achieved this?
ASPX
<div id="gg11" class="gauge"></div>
<meta http-equiv="refresh" content="5; URL=http://localhost:63738/main.aspx">
ASPX.cs
protected void Page_Load(object sender, EventArgs e)
{
JavaScriptMethod();
}
protected void JavaScriptMethod()
{
Calculations();
StringBuilder sb = new StringBuilder();
sb.Append("<script>");
sb.Append("var gg1 = new JustGage({");
sb.Append("id: \"gg11\",");
sb.Append("donut: 0,");
sb.Append("title: \"LAKE WALES\",");
sb.Append("titleFontColor: \"#000000\",");
sb.AppendFormat("value: {0},", percent);
sb.Append("min: 0,");
sb.Append("max: 100,");
sb.Append("labelFontColor: \"#000000\",");
sb.Append("humanFriendlyDecimal: 1,");
sb.Append("decimals: 1,");
sb.Append("symbol: \"%\",");
sb.Append("startAnimationType : \"bounce\",");
sb.Append("refreshAnimationType: \"bounce\",");
sb.Append("startAnimationTime: 1000,");
sb.Append("gaugeWidthScale: 1.2,");
sb.Append("customSectors: [{color: \"#ff0000\",lo: 0,hi: 79}, {color: \"#ffa500\",lo: 80,hi: 89}, {color: \"#1eae1e\",lo: 90,hi: 100}],");
sb.Append("counter: true");
sb.Append("});");
sb.Append("</script>");
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "temp", sb.ToString(), false);
}
Use a combination of JavaScript, jQuery and ASP.NET AJAX Page Methods, like this:
Markup:
<div id="gg11" class="gauge"></div>
JavaScript:
$(document).ready(function() {
setInterval(doAjax, 5000);
});
function doAjax() {
$.ajax({
type: "POST",
url: "YourPageName.aspx/GetGage",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(result) {
if (result.hasOwnProperty("d")) {
// The .d is part of the result so reference it
// to get to the actual JSON data of interest
// Put result into DIV
$('#gg11').html(result.d);
}
else {
// No .d; so just use result
// Put result into DIV
$('#gg11').html(result);
}
}
});
}
Note: You will need to change the name of YourPageName.aspx to the name of your .aspx page. Also, the .d syntax was an anti-XSS protection put in by Microsoft in the ASP.NET 3.5 release of ASP.NET AJAX; therefore the check to see if the .d property is there or not.
Code-behind:
[WebMethod]
public static string GetGage()
{
Calculations();
StringBuilder sb = new StringBuilder();
sb.Append("<script>");
sb.Append("var gg1 = new JustGage({");
sb.Append("id: \"gg11\",");
sb.Append("donut: 0,");
sb.Append("title: \"LAKE WALES\",");
sb.Append("titleFontColor: \"#000000\",");
sb.AppendFormat("value: {0},", percent);
sb.Append("min: 0,");
sb.Append("max: 100,");
sb.Append("labelFontColor: \"#000000\",");
sb.Append("humanFriendlyDecimal: 1,");
sb.Append("decimals: 1,");
sb.Append("symbol: \"%\",");
sb.Append("startAnimationType : \"bounce\",");
sb.Append("refreshAnimationType: \"bounce\",");
sb.Append("startAnimationTime: 1000,");
sb.Append("gaugeWidthScale: 1.2,");
sb.Append("customSectors: [{color: \"#ff0000\",lo: 0,hi: 79}, {color: \"#ffa500\",lo: 80,hi: 89}, {color: \"#1eae1e\",lo: 90,hi: 100}],");
sb.Append("counter: true");
sb.Append("});");
sb.Append("</script>");
return sb.ToString();
}
Use the javascript setInterval method to make an ajax call to your server where your sever page returns the HTML markup for the specific part you are interested in. Remove the meta tag which refreshes the whole page.
Assuming you have jQuery loaded in your page
$(function(){
var intId= setInterval(function(){
$("#gg11").load("getgauge.aspx");}, 5000);
});
This will keep sending an ajax request to the server page every 5 seconds!
You should have the getgauge.aspx returns the HTML markup you want to show in the UI.
If you are interested in only the changed value (whenever some value is changed in server), You may look into libraries like SignalR which makes realtime communication an easy task.
Related
I took a HTML string from tinyMCE and wrapped it with jQuery html(). I am now trying to unwrap it and display it in the the view.
I get tinyMCE contents and put them into to a div. I then extract html contents of that div and pass it to my database via AJAX. I am now trying to convert the contents back into format that will allow me to display it properly.
<textarea name="tinycontent" class="form-control"
id="textFromContentEditor" value=""></textarea>
<div id="textContent" style="display:none"></div>
var sectionContent = tinyMCE.activeEditor.getContent();
sectionContent = $('#textContent').text(sectionContent).html();
$.ajax({
url: '/Home/CreateNoteContent',
async: false,
type: 'POST',
data: {
headerID: headerID,
categoryID: categoryID,
sectionContent: sectionContent
},
success: function (result) {
if (result == false) {
toastr.error("Cannot create new content")
} else {
toastr.success("Successfully created new content")
$("#feed-" + releaseID).trigger('click');
jumpTo(scrollPos);
}
}
});
My input into tinyMCE: Hello World
What gets stored in the db: <p>Hello World</p>
I want to be able to display just the text contents in the view.
I am certainly not very good at js, ajax and so on, but this is what I did in my project to display html in one of my divs from the pages -tag.
var blobs = document.getElementById('your-div-Id').innerHTML = "<h4>somethingRandom</h4>";
OBS! I believe this is javascript and therefor might not be the right solution.
Hope this helps!
I have five dropdownlists in form of html selects. The first binds at page load using jQuery, and the rest bind when the previous dropdown has been selected. I also have five hidden fields for each dropdown which stores the selected values.
My problem is that when I do a post back, i.e. click the "Search" button, I have to re-populate the dropdowns and select the correct values again by using the ID's in the hidden fields. So far, I've come up with no good way to do this.
In the .aspx page:
<select name="boxFunktionsnedsattning" id="boxFunktionsnedsattning" multiple="multiple </select>
<asp:TextBox ID="HiddenBoxFunktionsnedsattning" runat="server" />
<script type="text/javascript">
function boxFunktionsnedsattningPopulate() {
$.ajax({
type: "POST",
url: "Sok.aspx/getFunktionsnedsattningar",
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: LoadBoxFunktionsnedsattning,
failure: function (response) {
alert(response);
}
});
}
//============================================================================================================
function LoadBoxFunktionsnedsattning(response) {
var result = response.d;
var options = $("#boxFunktionsnedsattning");
options.text(''); // clear the box content before reloading
if ($('#boxFunktionsnedsattning').val != '') {
options.removeAttr("disabled");
options.multipleSelect("enable");
}
else {
options.attr("disabled", true);
options.multipleSelect("disable");
}
$.each(result, function () {
options.append($("<option />").val(this.id).text(this.name));
});
UpdateBoxEnabledState();
options.multipleSelect("refresh");
}
</script>
Backend code:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static Funktionsnedsattning[] getFunktionsnedsattningar()
{
GetDataService.IgetDataClient gdc = new IgetDataClient();
return gdc.getFunktionsnedsattningAll();
}
I should add that I'm a beginner when it comes to jQuery, so there is probably something I've overlooked.
IF your using webforms use an onclick function to post back to the server instead of a submit. I think this is the functionality you want because the variables in the inputs of the form will keep its value. Is the search button returning results on the same page or a different one because it will determine the ease in which you can keep varibles during a post back. Good luck!
Got it working with the following solution:
function fillFunktionsnedsattning() {
//stores the value of selected items
var $fn = $('#<%=HiddenBoxFunktionsnedsattning.ClientID%>');
//creates an array of the values in the hidden field
var fnSplit = $fn.val().split(",");
//val() accepts an array which it uses to select items in the list (go figure)
$("#boxFunktionsnedsattning").val(fnSplit);
$("#boxFunktionsnedsattning").multipleSelect("refresh");
//function that triggers the binding of the next dropdown
boxFunktionsnedsattningOnChange();
}
For it to work, this function needs to be called in the function that populates the dropdown. Each dropdown needs it's own fillFunction to be called in the same place, like this, for an example:
function LoadBoxFunktionsnedsattning(response) {
var result = response.d;
var options = $("#boxFunktionsnedsattning");
options.text(''); // clear the box content before reloading
if ($('#boxFunktionsnedsattning').val != '') {
options.removeAttr("disabled");
options.multipleSelect("enable");
}
else {
options.attr("disabled", true);
options.multipleSelect("disable");
}
$.each(result, function () {
options.append($("<option />").val(this.id).text(this.name));
});
fillFunktionsnedsattning();
UpdateBoxEnabledState();
options.multipleSelect("refresh");
It's probably possible to simplify this, but this works for me.
I am trying to get access a drop-down that is in aspx page from static web method but it seems i can't get access and not what am i doing wrong. I want to set the dropdown index value to -1. thanks
this is what i am trying to do:
[System.Web.Services.WebMethod]
public static void Cancel()
{
myDDL.SelectedIndex = -1;
}
here is the javascript call
<script type="text/javascript" language="javascript">
function Func() {
//alert("hello!")
var result = confirm('WARNING');
if (result) {
//click ok button
PageMethods.Delete();
}
else {
//click cancel button
PageMethods.Cancel();
}
}
</script>
I am trying to get access a drop-down that is in aspx page from static web method
the web method in asp.net page are static, this mean are executed without page context(not completely true, you can access to Session), so what you need its retrieve result from web method, then make your update client side, something like(not tested, sorry):
jQuery.ajax({
url: 'callAJAX.aspx/Cancel',
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
var result = data.d.result;
$('#yourDropDownID')[0].selectedIndex = result;
}
});
It should be myDDL.selectedIndex = -1;
You cannot access a control inside webmethod..At the web service method level you cannot see anything about the page structure..
You can try this code for clearing dropdown..
Instead of calling pagemethod Cancel you can clear it inside javascript function itself..
var ddl = document.getElementById('myDDL');
ddl.options[ddl.selectedIndex] = 0;
Refer this link for extra reading..
I have a user control that will load via
public static string RenderControl(Control control)
{
var controlWriter = new StringWriter();
var htmlWriter = new Html32TextWriter(tw);
control.RenderControl(writer);
htmlWriter.Close();
return controlWriter.ToString();
}
AJAX used to write the html
$('#testDiv').html(result.d);
This is called through an ajax Post. It loads the user control fine, but since the javascript document load has already fired I cannot use jquery's document.Ready.
My situation is I need to load a user control dynamically and have jquery document.ready fire , or some equivalent. I would rather not use an updatepanel but if that is the only means of getting this done then that is what I will use.
What is an elegant solution to my problem?
You can use the built-in jQuery ajaxStop event to fire when an ajax call completes.
http://api.jquery.com/ajaxStop/
I solved something similar with a custom event that fires after the ajax contents were loaded and displayed.
Trigger the event inside the ajax function, after load and display:
$(document).trigger('ajaxLoadCallback');
And catch it in your document.ready script:
$(document).on('ajaxLoadCallback', function() {
// Your ready functions
}
If you create a function for everything that should be executed after document.ready than you can call this function (e.g. readyFunctions()) on document.ready and after the firing custom event.
public partial class Default : Page
{
[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToString();
}
}
$(function(){
$.ajax({
type: "POST",
url: "Default.aspx/GetDate",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do something interesting here.
}
});
});
How would I raise an event if my html syntax is the following:
<select runat="server" id="selection" onclick="inputCheck" />
I tried this in the code behind:
protected void inputCheck(object sender, EventArgs e)
{
//doesnt matter because it raised an on click.
}
Exception:Microsoft JScript runtime error: 'inputCheck' is undefined
Here is an example with jQuery posting back to the server using ajax method, very clean and easy to use. Let me know if you have questions.
--HTML page
<select id="selection" name="selection" />
--Place this following code in the head tag in the html surrounded by the script tags; you must also include the latest jquery code (free download from http://www.jquery.com)
$(document).ready(function()
{
$("#selection").click(function()
{
var selectionValue = $(this).val();
$.ajax({
type: "POST",
url: "CodeBehindPage.aspx/WebMethodName",
data: "{'input':'" + selectionValue + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
//return value goes here if any
}
});
}
});
//Code behind page
[System.Web.Services.WebMethod]
public static bool WebMethodName(string input)
{
try
{
//do something here with the input
return (true);
}
catch(Exception ex)
{
throw ex;
}
}
--This will post the code to the server without any postbacks, which I like. In order to test, set a break point inside of the WebMethodName function and view the input passed in. HTH
The onclick in your first snippet runs only in javascript. To raise the event server-side, the first step is to build a javascript method for this event. From there, you have a few options:
You can build an ajax request to call a WebMethod
You can post the event back to the original page. Since you aren't using asp control, you will have to have code in your page_load to check the posted data for the event and raise it on your own.