ajax call is continuously running - c#

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.

Related

Adding a script to a page on exit using Ajax. The script loads, but doesn't work through the ajax method?

When the users try to exit the page, I want to load a new script into my page.
The script successfully gets adding to the page, but it simply doesn't work properly. Now, if I just put the script into my page from the get-go, not using ajax, it does work. To me, this makes absolutely no sense, but something in my method/jQuery is clearly screwing the script up.
Lines from the JS file which Ajax doesn't seem to like:
document.write('<div id="' + token + '"></div>');
that.div.style.position = 'relative';
Error includes
Uncaught TypeError: Cannot read property 'style' of null
I'm assuming it's related to the script not being loaded onload? :S
This is my code
My Web Method.
[WebMethod]
public string webcamLink(string cat)
{
string script = "<script src=\"thescipt.js\"></script>";
return script;
}
This is my jQuery.
setTimeout(() => {
$(document).on("mouseout", evt => {
if (evt.toElement === null && evt.relatedTarget === null) {
$(evt.currentTarget).off("mouseout");
// An intent to exit has happened
$("#myNav").css("display", "block");
var cat = "cat";
var t = JSON.stringify({
'cat': cat
});
$.ajax({
type: "POST",
url: '/webServices/pop-up.asmx/webcamLink',
data: t,
cache: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
error: OnError,
timeout: 15000,
async: true
});
}
});
}, 5000);
function OnSuccess(data) {
$('#cams').html(data.d);
};
And my HTML:
<div id="cams" class="container-fluid"></div>
Does anybody have any idea what I'm doing wrong? I apologise if I'm being silly, quite new to this.

get list response from ajax call c#

I need to use the info from the list returned in a method that calls my ajax to c#.
This is the method, seems working fine:
public JsonResult getComandes(int id)
{
using (var db = new daw_tenda()) //estat 1 = acabat, estat 2 = en curs.
{
var llistacomandes = db.Comandes.Where(x => x.usuaris_id == id).ToList();
return Json(llistacomandes.ToList(), JsonRequestBehavior.AllowGet);
}
}
This is my ajax:
$.ajax({
url: "/Perfil/getComandes",
type: 'get',
dataType: 'json',
data: {
id: $("#idsesion").val()
},
success: function (response) {
$("#contingutcomandes").show();
$("#contingutperfil").hide();
if (response)
{
console.log(response);
}
}
});
I'm not getting any response, neither it's working first two jquery show and hide and i don't know what am i doing wrong, my method is working fine and is returning the list but i can't get it from the ajax call, what i have to fix?
Hmm -- since the method is correctly returning the list, the symptoms suggest the success function isn't being called. Have you tried changing success to complete? This'll execute even if the request is failing, which may shed some light.
Maybe something like:
complete: function(resp){
console.log("Ding!");
console.log(resp);
}

How to poll to WebMethod using Jquery/Javascript

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;
}

Ajax request doesn't work all times

So I have a number inside a div like this
<div style="display:inline" id="contItems">0</div>
and I am updating this number depending on the amount of items there are inside this cart from the controller and I am returning an Int and I need to replace the number inside the Div with the new Int, so I did this Ajax request:
function CountItemsDiv() {
$.ajax({
type: "GET",
url: '/Cart/CountItems',
cache: false,
success: function (data) {
$('#contItems').html(data);
}
});
}
and I call this function CountItemsDiv() when page loads and also when the user adds or removes a product and it works... but not all the times, sometimes it will change the number but some others it will not, I would say it would work 60% of the times someone would click on Add or Remove, I've tried to set cache to false but it still does it, what else could this be?
Yes, you need async function in false,async false waiting for request with all items.
function CountItemsDiv() {
$.ajax({
type: "GET",
url: '/Cart/CountItems',
cache: false,
async : false,
success: function (data) {
$('#contItems').html(data);
}
});
}

Multiple Ajax Calls calling on multiple timeouts in one page

Summery: I have to get several data from a service(hosted on multiple servers) using C# and finally display them to the user/s, all on one page, using ajax call. Consider that the final display formats contains charts and progresses that have created by Jquery and styled by CSS.
Some Code:
// Once Called Here and Timer Will Go On
UpdateDataA();
function UpdateDataA() {
$.ajax({
type: "POST",
async: true,
url: "Default.aspx/GetData",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var $s = $(".second");
$s.val(r.d[0]).trigger("change");
updateProgressA(r.d[1]);
updateProgressB(r.d[2]);
updateNetworkData(bytesToSize(r.d[5], 2), bytesToSize(r.d[6], 2));
},
error: function (msg) {
alert(msg.error);
}
});
setTimeout(function () { UpdateDataA(); }, 1000);//Timer
}
Consider more calls like this.
Problem: Timer intervals doesn't update at intervals have set. One element updates correct then waits for others to complete while it shouldn't. But I need to update all continuously together. In this way, if one call crash, Others will be die.
Question: What can I do or What are my faults?
Note: I'm new to jquery and ajax.
Thank You previously
Neglect my comment about interval. I think u will need to keep track of your timers :
timerA = setTimeout(function () { UpdateDataA(); }, 1000);
and clear the in the update function till task is complete
var timerA;
// Once Called Here and Timer Will Go On
UpdateDataA();
function UpdateDataA() {
clearTimeout(timerA);
$.ajax({
type: "POST",
async: true,
url: "Default.aspx/GetData",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var $s = $(".second");
$s.val(r.d[0]).trigger("change");
updateProgressA(r.d[1]);
updateProgressB(r.d[2]);
updateNetworkData(bytesToSize(r.d[5], 2), bytesToSize(r.d[6], 2));
timerA = setTimeout(function () { UpdateDataA(); }, 1000);//Restart time after task is complete
},
error: function (msg) {
alert(msg.error);
}
});
}

Categories