JQuery $.ajax not bringing latest data - c#

I am using JQuery 1.7.2. I am using highchart for making live data chart.
I maked one C# page where on the page load I am writing some jSON format data which I am using in another page with the help ajax call for highcharts. I will run that ajax call inside function and in success event of ajax call I will make setTimeout after 1 minute to call again function, So I will get latest data every time. Until here everything works very good.
But I have issue lets say data I am getting data only for 4 hr at every 1 minute than I keep my browser open and come next day. That time my aspx page will start with new fresh data from zero, so my highcharts should automatically remove all points and should pushing new data but it is not doing that. When I refresh my page all will start working good. Is there anyway that it should refresh by itself
My code for ajax call is as follow
function recieveData() {
var pathArray = window.location.pathname.split( '/' );
var chart = $('#container').highcharts();
$.ajax({
url: '/' + pathArray[1] + '/HomePageChartData.aspx',
dataType: 'json',
cache: false,
success: function (data) {
chart.yAxis[0].setExtremes(data.minY, data.maxY, true, true);
chart.series[1].setData([]);
chart.series[1].name = data.lineSeriesName;
chart.series[0].setData([]);
chart.series[0].name = data.areaSeriesName;
for (var x in data.lineSeriesData) {
chart.series[1].addPoint([data.lineSeriesData[x][0], data.lineSeriesData[x][1]]);
}
for (var x in data.areaSeriesData) {
chart.series[0].addPoint([data.areaSeriesData[x][0], data.areaSeriesData[x][1]]);
}
setTimeout(recieveData, 60000);
}
});
}
##Edited with more explanation
It's look like I could not properly previously so I will do it again. My scenario is like data come between 9 AM to 12.30 PM and it remain on the database until next day 7 AM. So my highchart will get data every minute between 9 AM to 12.30 PM which is working very good without any problem. But issue when we wipe out all data at next day 7 AM and we start getting new data at 9 AM my high chart is not clearing by itself and start getting new data.
But if i refresh my browser I will get new data and it work good. So I was looking something like if we wipe all data my ajax should get alert and reload the page or clear data from highchart.
So I was looking for some event or way to do it in ajax call. Some guidance from experts.

Try using data parameter in your $.ajax call to send time, it will differentiate your each ajax call
data:{'time': new Date().getSeconds() }

You can compare actual time with next day, calculate interval, and then set timeout to reload page, code snippet:
var now = new Date(),
time = (new Date(now.getFullYear(), now.getMonth(), now.getDate()+1), 7).getTime() - now.getTime(); //calculate next day 00:07:00 in ms
setTimeout(function () {
document.location.reload(true);
}, time);

Related

Is there a way to detect if browser has been closed in a asp.net web mvc 5.0 project?

I am using tempdata for a variable and current have it set in the home controller and in my first last controller I have it removing that key by doing if(TempData.ContainsKey()) TempData.Remove(). I placed that there assuming the user will go from point A to point D where D is the last controller. But I noticed if I close the application throughout any point of the application that the tempdata that was assigned i.e. tempdata["username"] = username will contain the previous value that was entered from the original start of the program and then will be updated after user enters a value to update the key for tempdata. In a asp.net web mvc 5.0 project is there a way to check to see if a browser has been closed so that way I could remove the logic that is inside of the last controller that removes the key into the logic of checking if browser has been closed?
You can detect the tab/browser being closed from javascript using the beforeunload event. Credited Source
window.addEventListener('beforeunload', function (e) {
// User is closing the tab/browser
// You can cancel this event by using e.preventDefault();
// and for older browsers by using e.returnValue = '';
});
From there you can send a message back to your application using AJAX to handle the temp data removal.
Below using JQuery
$.ajax({
method: "POST",
url: "AbandonSession",
data: { someVar: "some val" }
})
.done(function( msg ) {
alert( "Session abandoned: " + msg );
});

Display consistently changing value on an ASP.NET web form

I am currently writing a program in C# that constantly outputs random values between 1 and 12 and displays them in a label control on an ASP.NET web form. While the output is successfully written to the web form, it only displays one value. In other words, I want the label output to track the output (display) each value that is produced by the function as written below to produce a consistently changing value:
[WebMethod]
public static string StreamData()
{
string[] value = new string[1];
Random rnd = new Random();
Thread t = new Thread(delegate ()
{
while (true)
{
value[0] = rnd.Next(1, 13) + "";
}
});
t.Start();
return value[0];
}
I have tried using an AJAX function to pull the data from the function but I am not too sure if I am going about displaying the data in the right way:
<script type="text/javascript">
$(function () {
$.ajax({
type: 'POST',
url: 'default.aspx/streamdata',
data: '',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
//alert(msg.d);
$('#<%= lblReading.ClientID %>').html(msg.d);
}
});
});
</script>
The program is being written to test the concept of trending live data from PLCs using TIA Portal 15 with said data obtained from sensor readings across a production line. The idea behind this program is to serve as a proof of concept that real-time data can in fact be displayed and trended in an ASP.NET web environment to be accessed across a range of web-compliant devices. Despite my efforts in displaying random values in this way, my attempts have been thus far unsuccessful, although I am determined to not give up. I researched this method which uses SignalR to achieve something similar to my desired solution, though I am unsure of how to implement it in my case: How to implement real time data for a web page
Could somebody please shed some light on how the above might be achieved?
Many Thanks,
Ben.
Your requirement can be accomplished in ASP.Net web forms using SignalR.
Please take a look at this small tutorial on how to do that,
Adding SignalR to an ASP.NET WebForms Project

How to Run JavaScript Function on page load

I have a program(c#) but the programs needs to work for every timezone, so i created a js script to know the client timezone and this is what i get (and it works) but only if only click action(example button), but i need this to work (run) on my page load is that possible?
This is my script
<script type="text/javascript">
function pageLoad() {
myFunction();
}
function myFunction() {
var localTime = new Date();
var year = localTime.getYear();
var month = localTime.getMonth() + 1;
var date = localTime.getDate();
var hours = localTime.getHours();
var minutes = localTime.getMinutes();
var seconds = localTime.getSeconds();
var calculated_date = hours + ":" + minutes + ":" + seconds;
var div = document.getElementById("demo");
div.innerText = calculated_date;
var client_date = document.getElementById("client_date");
client_date.setAttribute("value", calculated_date);
}
</script>
And this is what i tryed so far
Page.ClientScript.RegisterStartupScript(this.GetType(), "myFunction", "myFunction()", true);
Session["Data"] = client_date.Text;
Response.Redirect("Welcome.aspx");
Thanks anyway for reading my post, hope someone can help on this issue
Yes, it is possible. All you need is to use onload() event.
This would do it
<body onload="myFunction()">
<!-- body elements here -->
</body>
You can execute any function that you want to execute on a page load. I used myFunction because that had to be executed when the page loads.
with javascript
if (document.readyState === "complete") { myFunction(); }
with jquery
$(document).ready(function(){ myFunction(); });
The problem isn't what you think. In all likelihood, this JavaScript *is*set to run when the page loads. And it's probably going to do exactly what you told it to do. The problem is what else you're doing. Note these three lines:
Page.ClientScript.RegisterStartupScript(this.GetType(), "myFunction", "myFunction()", true);
Session["Data"] = client_date.Text;
Response.Redirect("Welcome.aspx");
What you're doing here is:
Set the JavaScript to run when the page loads.
Capture the value of a TextBox from before the page loaded.
Abandon the page entirely and redirect to another page.
So even if the JavaScript code would run, you're not capturing the value it sets. And even if you were capturing that value, you abandon the entire page before it even loads and redirect the user to a different page.
You need to better understand the difference between server-side code, which runs on the server in its entirety before delivering a page to the client... and client-side code, which runs after a page has loaded on the client.
If you need this information from the client, you'll need to get it from client-side code. This code will need to run in a loaded page and then send the value back to the server in some way. Either the page has to execute and then perform the redirect from client-side code, or (probably better) the page can run as normal, make an AJAX post to the server to notify you of this information (time zone), and then the server can respond to the AJAX request with any data the client-side code needs to adjust the page accordingly.
It's not really clear what you're customizing based on the time zone or when you need to know the time zone. But it is clear that you need the client-side code to execute before you can retrieve that value from the client.
Use System.Web.ScriptManager Like this :
Page.ClientScript.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "myFunction();", true);
Session["Data"] = client_date.Text;
Response.Redirect("Welcome.aspx");
Well you can't store the value within a hidden field and then read result, but what you can do is store the timezone offset as a cookie and then read that on the server after the page reloads.
This article explains it perfectly
http://prideparrot.com/blog/archive/2011/9/how_to_display_dates_and_times_in_clients_timezone

Replacing Timer text with result of DB calculation when Timer hits 00:00:00

I have a jQuery Countdown Timer that I am using, and I need to be able to access my Database and perform some calculations and then return the result:
$('#expireMessage').countdown({until: shortly,
expiryText: '<div class="over">It\'s all over</div>'});
$('#expireMessageStart').click(function() {
shortly = new Date();
shortly.setSeconds(shortly.getSeconds() + 5.5);
$('#expireMessage').countdown('change', {until: shortly});
});
Now, the above code just displays a countdown timer, and counts down. And when it hits
00:00:00
it displays a message "It's all over".
But what I need it to do is display a different message depending on the result of the DB calculations.
The DB work I can do, but I'm not sure how to go about retrieving that info from the database when using jQuery. I'd really appreciate your help.
Thank you
You need to set up something on the server side to talk to the database for you, then return the result in JSON format. What that something is depends on what your server-side code is written in. Are you using PHP? Java? ASP.NET?
I work primarily in ASP.NET, so one way I might tackle this is adding a WebMethod to my page that executes a database query, builds the message, serializes it to JSON, and returns it to the client.
In your JavaScript, you'll want to execute either an XMLHttpRequest (if you're using regular JavaScript) or a jQuery AJAX request.
Here's a very simple example of what a jQuery AJAX call might look like:
$.ajax({
url: 'http://mysite.com/getmymessage',
success: function( data ) {
// Here's where you'd update your countdown display, but I'm just writing to the console
console.log( 'The server says: ' + data.myDbResult );
}
});

How to do live update on section of page?

I need to refresh sections of my page to update when there is new data! what do i do? use jquery?
examples:
Yes, jQuery's great for this. Look into these methods:
http://api.jquery.com/category/ajax/
jQuery is usually not needed for basic AJAX. A simple example could be as follows:
liveSection = document.getElementById('latest-news');
request = new XMLHttpRequest;
request.open('GET', '/news-ajax', true);
request.send(null);
request.addEventListener('readystatechange', function() {
if (request.readyState == 4 && request.status == 200)
liveSection.innerHTML = request.responseText;
}, false);
If you're using Asp.NET, why not use an UpdatePanel? It's simple and reliable.
Edit
I just re-read your question and it looks (based on how you worded it) that you want to update a user's web page when the data changes on the server. I just want to make sure you understand that in a web app, the server can't trigger the browser to do anything. The server can only respond to browser requests, so you'll need to have the browser poll the server periodically.
I've created a simple example (using jQuery) to help you understand the breakdown of the things that will need to happen, which are:
1 - Periodically polling the server (via ajax) using Javascript's setTimeout to check that what is loaded into the browser is the latest content. We can achieve this by fetching the latest item ID or whatever and comparing it to a variable, which was initialised when the page first loaded.
2 - If the item ID does not match (a bit of an oversimplification) then we can assume that there has been an update, so we replace the content of some element with some content from some page.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
function getLatestStuff() {
// fetch the output from a context which gives us the latest id
$.get("isthereanupdate.aspx", function(response) {
// we have the response, now compare to the stored value
if(resp != lastItemId) {
// it's different, so update the variable and grab the latest content
lastItemId = response;
$("#latestStuffDiv").load("updates.aspx");
}
});
}
$(document).ready(function() {
// the value which initializes this comes from the server
var lastItemId = 7;
setTimeout(getLatestStuff, 10000);
});
</script>
If you want to update when there is new data, you should look into comet or pubsubhubbub. jQuery can help you display the data in a pretty way, but you'll need to write stuff on the serverside to send the data.

Categories

Resources