Asked by:
How to pass data from background service to javascript method?

Question
-
User-467044538 posted
Hi,
I have a background service method that runs with the purpose to pass data points to javascript chart plugin.
My question is, what's is the best way to do it?
Thanks.
Wednesday, June 12, 2019 9:40 AM
All replies
-
User475983607 posted
I think you are looking for a technology like SignalR.
https://docs.microsoft.com/en-us/aspnet/core/signalr/introduction?view=aspnetcore-2.2
Otherwise, you can send HTTP requests to check on the state of the service using jQuery/AJAX (XHR) or fetch.
Wednesday, June 12, 2019 10:34 AM -
User-1038772411 posted
Hi, Frank420
That's an easy and neat way of calling c# methods from Javascript. You can call that method using jQuery Ajax. See the below example for a webMethod.
[WebMethod] public static string RegisterUser(string s) { //do your stuff return stringResult; }
and then call this method using jQuery ajax. You can pass parameters also. like given below
function showDetail(kurz) { String sParam = kurz.toString(); $.ajax({ type: "POST", url: "PageName.aspx/MethodName", data: "{s:sParam}", // passing the parameter contentType: "application/json; charset=utf-8", dataType: "json", success: function(retValue) { // Do something with the return value from.Net method } }); }
Thanks.
Wednesday, June 12, 2019 11:29 AM -
User753101303 posted
Hi,
There is rarely a "best" way. Most often this is a tradeoff. If enough you could just refresh the page on a regular interval (and maybe adapting the delay depending on past events). A more complex solution could be to push data (or just a refresh event) from the server side using SignalR.
Or be explicit if the problem is rather between the server side and this background service ?
Wednesday, June 12, 2019 11:34 AM -
User61956409 posted
Hi Frank420,
I have a background service method that runs with the purpose to pass data points to javascript chart plugin.
My question is, what's is the best way to do it?
Please clarify more about your scenario and requirement, if your background service just exposes HTTP services and data for serving up chart plugin on web pages, as others mentioned, you can make http request(s) from your JavaScript client via AJAX etc.
Besides, if you'd like to let your background service push data to clients and update chart plugin automatically, you can try to implement server broadcast functionality using SignalR.
- [Server broadcast with SignalR 2](https://docs.microsoft.com/en-us/aspnet/signalr/overview/getting-started/tutorial-server-broadcast-with-signalr)
With Regards,
Fei Han
Thursday, June 13, 2019 1:50 AM