setTimeout calls function repeatedly and causes page to hang - spring-mvc

I have three javascript functions defined that creates ajax calls to my java controller. I set timeouts for two of the functions to update the ping status every 3 seconds and to update performance status every 5 min. The ping update every 3 seconds seems to be working correctly but when the updatePerformance method gets called my controller method gets executed 5 or so times in a row until the app hangs. Any ideas why one is working and the other setTimeout isn't? Here's my javascript functions:
<script type="text/javascript">
function updateReachability() {
$.ajax({
url: 'updatePing.htm',
type: 'GET',
success: function(data) {
$('#site').html(data);
}
});
}
setTimeout(updateReachability, 3000);
function updatePerformance() {
$.ajax({
url: 'updatePerformance.htm',
type: 'GET',
success: function(data) {
$('#site').html(data);
}
});
}
setTimeout(updatePerformance, 300000);
function updateSiteList() {
$.ajax({
url: 'connector.htm',
type: 'GET',
success: function(data) {
$('#site').html(data);
}
});
}

you may want to wrap you function in the setTimeout itself, so that the settimeout is specific to that function and nothing else.
<script type="text/javascript">
function updateReachability() {
setTimeout(function() {
$.ajax({
url: 'updatePing.htm',
type: 'GET',
success: function(data) {
$('#site').html(data);
}
});
},3000);
May be this will work for you.

Don't know why this works but created a separate function that sets the two timeout values then called it on body onload:
<script type="text/javascript">
function updateSiteList() {
$.ajax({
url: 'connector.htm',
type: 'GET',
success: function(data) {
$('#site').html(data);
}
});
}
function updateReachability() {
$.ajax({
url: 'updatePing.htm',
type: 'GET',
success: function(data) {
$('#site').html(data);
}
});
}
function setTimeouts() {
setInterval(updateReachability, 3000);
setInterval(updatePerformance, 300000);
}
function updatePerformance() {
$.ajax({
url: 'updatePerformance.htm',
type: 'GET',
success: function(data) {
$('#site').html(data);
}
});
}

Related

asp.net mvc core add anchor tag in success function in ajax

It's not a working properly anchor tag in the success function of ajax in jquery. Button clicked but not perform action.
<script>
$(document).ready(function () {
$.ajax({
type: "GET",
url: "#Url.Action("Action", "Controller")",
dataType: "json",
success: function (data) {
$.each(data.models, function (index, value) {
$('#Teacher_table tbody').append("<tr><td> <a asp-action='Action_name' asp-route-id="+value.Id +">Edit</a></td></tr>");
});
}
});
});
I find the solution to this problem.
asp-action is not work in success function in asp.net MVC core. So use this code
<script>
$(document).ready(function () {
$.ajax({
type: "GET",
url: "#Url.Action("Action", "Controller")",
dataType: "json",
success: function (data) {
$.each(data.models, function (index, value) {
$('#Teacher_table tbody').append("<tr><td><a href='/Controller/Action?id=" + Id + "'>Anchor Name</a></td></tr>");
});
}
});
});

How to send ember js header request without ember data

I'm trying to make a call to the wp-api.org plugin for Wordpress. I want to show all users, and I want to use cookie authentication. Therefore I need to send a header request as explained on the website like this:
options.beforeSend = function(xhr) {
xhr.setRequestHeader('X-WP-Nonce', WP_API_Settings.nonce);
if (beforeSend) {
return beforeSend.apply(this, arguments);
}
};
The following code I am using in my model:
App.UsersRoute = Ember.Route.extend({
model: function() {
return Ember.$.ajax({
url: "http://myurl.com/wp-json/users/",
type: "GET",
dataType: "json",
data: JSON.stringify({}),
beforeSend: xhr.setRequestHeader('X-WP-Nonce', WP_API_Settings.nonce);
});
}
});
At the moment the site returns this message because the authentication failed, but I am logged in and cookies are set:
[{"code":"json_user_cannot_list","message":"Sorry, you are not allowed to list users."}]
This should work:
App.UsersRoute = Ember.Route.extend({
model: function() {
return Ember.$.ajax({
url: "http://myurl.com/wp-json/users/",
type: "GET",
dataType: "json",
data: JSON.stringify({}),
beforeSend: function(xhr) {
xhr.setRequestHeader('X-WP-Nonce', WP_API_Settings.nonce);
}
});
}
});
the beforeSend property needs to be a function that is passed xhr, like in your first example, in your second code snippet xhr will be undefined.

Asynchronous ajax call causing issue in KnockOutjs

I have a button on click of that i am calling something like :
ViewModel:
self.MyArray = ko.observableArray();
self.remove = function(c) {
ko.utils.arrayForEach(c.sData(), function(ser) {
if (ser.Check() == true) {
self.MyArray.push(service);
count++;
}
});
if (count) {
$.ajax({
url: "/api/LoadCustomer/?reason=" + reason,
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: ko.toJSON(self.MyArray),
success: function(data) {
ko.utils.arrayForEach(self.MyArray(), function(removedata) {
c.sData.remove(removedata);
});
}
});
self.MyArray([]);
}
};
If i include async:false in my ajax call i get everything fine but if i didn't include async (its default property is true) i dont know somehow in my success function of ajax call self.MyArray() remains Empty but its not the case if i keep it false (Awkward).
Sometimes i fear like if i have series of ajax calls with async:true while loading into a observable array(OnLoad) there may be a slight chance of misplacement of data .
Help me understand .
The reason your observable array MyArray is empty sometimes is because this line of code self.MyArray([]); executing before the ajax call is done. How about this instead -
if (count) {
$.ajax({
url: "/api/LoadCustomer/?reason=" + reason,
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: ko.toJSON(self.MyArray),
success: function (data) {
ko.utils.arrayForEach(self.MyArray(), function (removedata) {
c.sData.remove(removedata);
});
},
complete: function() { // complete fires after success and error callbacks
self.MyArray([]); // empty the array no matter what happens (error or success)
}
});
}

jquery Post does not work in asp.net mvc 3?

I just copied some code from an asp.net mvc 2 app which works. Now i am trying it in asp.net mvc 3 and it does not call the save method on the controller?
controller:
[HttpPost]
public JsonResult save(string inputdata)
{
return Json(new { Result = string.Format("From the controller - you have clicked the GO-button ! ") }, JsonRequestBehavior.AllowGet);
}
view:
<button id="but">go</button>
<div id=result></div>
<script type="text/javascript">
$(document).ready(
$("#but").click(
function () {
$.ajax({
url: "/Home/save",
dataType: "json",
type: 'POST',
data: "test",
success: function (result) {
$("#result").html(result.Result);
}
});
}
)
);
</script>
You are not passing the data correctly. The action argument is called inputdata. So you should use this same name in the data hash of the AJAX request:
$.ajax({
url: '/Home/save',
dataType: 'json',
type: 'POST',
data: { inputdata: 'test' },
success: function (result) {
$('#result').html(result.Result);
}
});
Also never hardcode urls in your javascript, always use url helpers or your application will simply stop working when you deploy due to the possibility of having a virtual directory name:
$.ajax({
url: '#Url.Action("save", "home")',
dataType: 'json',
type: 'POST',
data: { inputdata: 'test' },
success: function (result) {
$('#result').html(result.Result);
}
});
Another issue that you have with your code is that you are not canceling the default action of the button meaning that if this is an action link or a submit button the AJAX request might never have the time to execute before the browser redirects.
Also you don't need to specify the dataType to JSON as jQuery is intelligent enough to deduce this from the Content-Type response header sent from the server.
So the final version should look something along the lines of:
<script type="text/javascript">
$(function() {
$('#but').click(function () {
$.ajax({
url: '#Url.Action("save", "home")',
type: 'POST',
data: { inputdata: 'test' },
success: function (result) {
$('#result').html(result.Result);
}
});
return false;
});
});
</script>

getting data as the page loads

I'm trying to get data back after an element is ready in the DOM. I'm trying to use the load function from JQUERY but I get a message .load() is not a function.
Is there a best practice when using ajax to get data for an element (in my case a div) during a page load? I'm using ASP.NET and calling a webmethod in code behind.
Here is my ajax/jquery code:
$(document).ready(function () {
$(function () {
$("[id$=divArea]").load()(function () {
$.ajax({
type: "POST",
url: "apage.aspx/Role",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (response) {
alert("got data from Role");
},
error: function (data) {
alert("failed to get data from Role");
}
});
});
});
Thanks.
$(document).ready() is for calling code once the DOM is ready - therefore, if I have understood you correctly, you don't need to include $("[id$=divArea]").load()(function () {
It should work like this:
$(document).ready(function () {
$(function () {
$.ajax({
type: "POST",
url: "apage.aspx/Role",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (response) {
alert("got data from Role");
},
error: function (data) {
alert("failed to get data from Role");
}
});
});
});
By the way - it was probably a paste error, but you also omitted the $(document).ready closing }); in the code you posted.
I think that the problem it's the code itself, try the code like this
$(document).ready(function (){
$("[id$=divArea]").load('apage.aspx/Role',function(response, status, xhr) {
if (status == "error") {
var msg = "Sorry but there was an error: ";
$("#error").html(msg + xhr.status + " " + xhr.statusText);
})
});

Resources