Can anyone tell me about how to poll to webMethod on specific interval using Javascript/JQuery ? I tried setInterval & setTimeOut but non of them is working for me. My application generates reports on user's request. since the report generation is taking 10-15 minutes I dont want to block UI thread so I create a reportID on button click from javascript and using _dopostback to call button click event and pass the reportID to it. C# button click event calls generate_report() function using Delegate/BeginInvoke and now I want to poll to WebMethod I have created inorder to get the report... here is a code snippet..
$("#btn1").click(function () {
var ReportID = generateReportID();
__doPostBack("<%= btnGenerate.UniqueID %>", ReportID);
IntervalID = setInterval(function () { Poll(ReportID); }, 30000);
});
function Poll(id) {
$.ajax({
type: "POST",
url: "Default.aspx/WebMethod",
data: "{'ReportID','" + id + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
// Check if report is ready
// If not poll again after 30 secs
// If report is ready Get the Report and clearInterval
},
failure: function (error) {
}
});
};
[WebMethod]
public static string WebMethod(string ReportID)
{
if (ResultSet.ContainsKey(int.Parse(ReportID)))
{
return "Ready";
}
else
{
return "NotReady";
}
}
So On button click how do I start poll to this web method after every 30 secs till report is "Ready" and clear the interval after once its ready. ??
SetInterval was working fine, PostBack was the culprit.... subsequent postbacks i.e. button clicks would kill the previous setintervals.... so now I pass all the ReportIDs to codebehind on button click function and setIntevals using client script
Page.ClientScript.RegisterStartupScript(typeof(Page), "test" + UniqueID, "setInterval(function () { Poll(ReportID); }, 30000);", true);
alternative to send ReportIDs to code behind functions and looping through and setting interval foreach ReportIDs using client script, one can also save ReportIDs in localStorage so that its available in subsequent postbacks.
NOTE : Thanks a tonn for your help #Krzysztof Safjanowski
Use SetTimeout to call itself recursively, until you have the result you want.
Ex:
function initPoll()
{
setTimeout(pollWebServer(), 30000);
}
function pollWebServer()
{
if(!checkResult())
setTimeout(pollWebServer(), 30000);
}
function checkResult()
{
//Do some work to check result that you are looking for
//This is where you would check your Web Method using jQuery
return false;
}
Related
im trying to get the value each time a client selects a option from my Dropdown list to send it back to controller where i use the value on creating a file and then refreshing the page but im unable to do so
This is my Dropdownlist:
<select id="sel0">
<option value="">Todos</option>
#foreach (var item in Model.Select(l => l.Fecha).Distinct())
{
<option value="#lines">#lines</option>
}
</select>
This is my Ajax Call:
$('#sel0').on('change', function () {
dataTable.columns('.fechas').search(this.value).draw();
});
$("form").submit(function () {
$.ajax({
url: '#Url.Action("MethodName","HomePosController")',
type: 'POST',
cache: false,
data: { Selected: $("#sel0").val() },
success: function (data) {
//
}
});
});
and this is my Controller its named 'HomePosController':
public ActionResult MethodName(string Selected)
{
var db = new ArponClientPosContext();
String value = Selected;
var json4 = JsonConvert.SerializeObject(Selected);
System.IO.File.WriteAllText(#"C:\inetpub\wwwroot\potzolcalli.brain.arpon.com\valorselected.txt", json4);
return View("~/Views/HomePos/Index.cshtml", db.Pos.ToList());
}
But whenever y select a option of my dropdown nothing happens, the page its not refreshed nor the file is created what am i doing wrong?
If you want it to be on dropdown change then you have to send ajax call in change event :
$('#sel0').on('change', function () {
dataTable.columns('.fechas').search(this.value).draw();
$.ajax({
url: '#Url.Action("MethodName","HomePos")',
type: 'POST',
cache: false,
data: { Selected: $("#sel0").val() },
success: function (data) {
//
}
});
and you have to not write complete Controller class name, you have to skip the Controller postfix, it is convention which is followed by Url helpers in mvc, that way your url generated will be wrong and ajax call will fail.
whenever y select a option of my dropdown nothing happens
Well, this happens:
dataTable.columns('.fechas').search(this.value).draw();
But that doesn't invoke the AJAX request. It doesn't do much of anything, really.
how can i trigger the ajax ? i want it to trigger after a value is changed in the dropdown list
In that case you want to do that on the select element's change event. Currently you perform the AJAX request here:
$("form").submit(function () {
// AJAX
});
That is, you perform the request in the form's submit event. Just add it to the drop down's change event instead:
$('#sel0').on('change', function () {
dataTable.columns('.fechas').search(this.value).draw();
$.ajax({
url: '#Url.Action("MethodName","HomePosController")',
type: 'POST',
cache: false,
data: { Selected: $("#sel0").val() },
success: function (data) {
//
}
});
});
the page its not refreshed
Well, no. That won't happen in an AJAX request. Currently your success callback is empty, so nothing will happen on the page. Whatever you want to happen would need to be put in that callback.
I want to receive notification from database when table is updated but I need a background thread which call after 1 mint and check database table and show me notification. How can I implement a background thread? I have implemented a thread but when I use while(true) in it, my form is not loaded keep on processing.
Code:
protected void Page_Load(object sender, EventArgs e)
{
t1 = new Thread(new ThreadStart(Function1));
t1.IsBackground = true;
t1.Start();
}
private void Function1()
{
while (true)
{
Thread.Sleep(2000);
count++;
Label1.Text = "Function" + count;
}
}
You have a fundamental misunderstanding of the difference between server-side and client-side code.
For example, your request would require a framework such as SignalR to push a real-time notification to a client.
The easier method is to use Javascript to poll a page of your choice.. for example (jQuery, obviously):
// I'm not a huge jQuery person so theres probably a jQuery way to do this
setInterval(function() {
$.get('/yourPage.aspx', function(response) {
if (response.success) {
alert(response.message);
}
});
}, 5000); // poll a page every 5 seconds.
Then your C# page at /yourPage.aspx can check the database and return a Json object with the properties I've mentioned above.
You need to read up on the difference between Client Side and Server Side.. and how they interact in a stateless protocol such as HTTP.
You can not use background thread on asp.net page. It works on http stateless protocol and the page object is not available after the response it sent. You can only send one response against one request. You can use jQuery ajax , asp.net ajax library timer control or web sockets to fetch data from server periodically.
This post explains how you can fetch data from server using jQuery ajax. This is also very good tutorial to get the data from server using web methods. The example from this tutorial is given below.
Code behind
public partial class _Default : Page
{
[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToString();
}
}
Javascript
$(document).ready(function() {
// Add the page method call as an onclick handler for the div.
$("#Result").click(function() {
$.ajax({
type: "POST",
url: "Default.aspx/GetDate",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Replace the div's content with the page method's return.
$("#Result").text(msg.d);
}
});
});
});
You can do async tasks in ASP.NET if you are using the 4.5 framework:
http://www.hanselman.com/blog/TheMagicOfUsingAsynchronousMethodsInASPNET45PlusAnImportantGotcha.aspx
I'm using ajax to check whether there is no new alerts stored in my sql database. I've set it to run every 30 seconds but instead it keeps on calling the function that checks the database every second. Here is my code.
This is code in the view. "_Tasks" is my partial view and it will be the view that is going to be updated. I haven't done anything for a success return because it never reaches that code.
#Html.Action("_Tasks")
<script type="text/javascript">
(function poll() {
$.ajax({
type: 'GET',
cache: false,
url: '#Url.Action("TasksRefresh")',
dataType: "json",
complete: poll,
timeout: 30000,
success: function (data) {
if (data.success == true)
alert("Hello");
}
});
})();
</script>
This is in the controller
public JsonResult TasksRefresh()
{
var alerts = getAlerts();
var cache = HttpRuntime.Cache["Tasks"];
if ( cache == alerts)
{
return Json(new
{
success = false,
});
}
else
{
return Json(new
{
success = true,
// View = this.Re
});
}
}
Try this:
(function poll() {
$.ajax({
type: 'GET',
cache: false,
url: '#Url.Action("TasksRefresh")',
dataType: "json",
complete: function () { setTimeout(poll, 30000); }, // Changed, call poll again when 30s has pasted
timeout: 30000, // This just says it fails if the request takes more than 30s
success: function (data) {
if (data.success == true)
alert("Hello");
}
});
})();
Timeout is not a delay. Timeout is how long it should wait before considering the request a failure. By setting complete to poll, you are telling it to immediately make another call. You need to put a delay in your complete function.
What I can guess is, you are executing the poll function again on complete of the ajax call. It might just take a second to complete that ajax call. You can use the timer at javascript code. try using settimeout or setInterval. And do ajax call in that timer. See if is helpful.
timeout: 30000 is just to make sure that your ajax call would wait for response for maximum of that much time.
You are executing your poll function as soon as ajax call completes that is why calls are made so quick.
Ok, this is my problem :).
I have couple of [WebMethods] in my code behind and using jquery ajax to get data from server.
And then it happens :). After some time while page is inactive when i try to click on button which should have send request to server it simply does nothing for about half of minute and only then event is fired and i get response from server.
my javascript looks something like this:
addToCart.click(function () {
AddOrRemoveItemToCart($(this));
});
function AddOrRemoveItemToCart(control)
{
var itemId = contol.attr("id");
$('document').ready(function () {
$.ajax({
type: "POST",
url: "Home.aspx/AddOrRemoveItemToCart",
data: "{itemId:" + itemId + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data.d.length > 0) {
SucessAddItemToCart(data.d);
}
},
error: function (textStatus) {
alert(textStatus);
}
});
});
}
function SucessAddItemToCart(data)
{
//DO SOMETHING WITH DATA
}
And my server side code look something like:
[WebMethod]
public static List<CartItem> AddOrRemoveItemToCart(string itemId)
{
List<CartItem> items = new List<CartItem>();
List<CartItem>temp = new List<CartItem>();
bool check = false;
if(HttpContext.Current.Session["items"]!=null)
{
items = (List<CartItem>)HttpContext.Current.Session["items"];
foreach(CartItem c in items)
{
if(c.Id != itemId)
temp.Add(c);
else
check = true;
}
if(!check)
temp.Add(new CartItem{Id = itemId});
}
HttpContext.Current.Session["items"]=temp;
return temp;
}
Normally I would have said your Session expired. But since the event fires after half a minute, it has to be something else.
Try to debug with Firebug and check if AddOrRemoveItemToCart gets called immediately. You can also see the traffic between the browser and the server.
Your event should fire immediately but as Remy said your Session has probably expired, and it takes some time to re-establish the session object and process the request.
Im new to jquery and stuck with what i want to achieve.
Heres what I want to do using jquery and asp.net mvc.
click a submit button
this calls an action method called LogOn in the controller Account
if the call allows users to log in succesfully redirect to a url (sepecified by LogOn)
if it fails replace a div(with id="error") with "sorry error occured"
so far I tried this:
$("#submit")
.button()
.click(function () {
$.ajax({
type: "POST",
url: "Account/LogOn",
dataType: "json",
success: function (data, textStatus) {
if (data.redirect) {
// data.redirect contains the string URL to redirect to
window.location.href = data.redirect;
}
else {
// data.form contains the HTML for the replacement form
$("#error2").replaceWith(data.error);
}
}
});
});
how do I construct the relevant bits in the action method? to make this work?
and is the jquery code ok? i suspect prob not.
Thanks
If you want to redirect asp.net page at same directory , you can by Jquery/Java script by this :
$("#ctl00_iframecontent_BtnCancle").click(function () {
window.location = "IncSLAList.aspx?bi=37";
});
and
To redirect to Another page of project , can use :
window.location.href = "http://ImageUpload/Welcome.aspx?
Your jQuery is almost correct:
Don't call .button() (unless you're using jQuery UI and want to do that)
Add return false; at the end of the click handler to prevent the browser from submitting normally.
In the action, you would either return Json(new { redirect = str }) or return Json(new { error = str }).