Continuous ajax calls makes application crash - javascript

I have a html application which contains 4 ajax calls which runs continously every 2 seconds back to back. The objective is to read new and fresh data fron the db continuously and seamlessly.
function messagesreceived(){
var queryString = "XXXXXXXXX";
$.ajax({
url:queryString,
'Content-Type':'application/json',
method:'GET',
dataType:'json',
cache: false,
success:function(data){
displaymessages(data);
rendermessagesreceived();
},
complete: function(xhr,status){
setTimeout(messagesreceived,2000);
},
error: function(xhr,status){
if(xhr.status == 0){
footerText.setText("NETWORK DISCONNECTED");
}else{
footerText.setText("Something went wrong! Please reload the page!");
}
}
});
}
function loadreadings() {
var queryString = "XXXXXXX";
$.ajax({
url: queryString,
'Content-Type': 'application/json',
method: 'GET',
dataType: 'json',
cache: false,
success: function(data) {
mapreadings(data);
plotreadings();
},
complete: function(xhr, status) {
setTimeout(loadreadings, 2000);
},
error: function(xhr, status) {
if (xhr.status == 0) {
footerText.setText("NETWORK DISCONNECTED");
} else {
footerText.setText("Something went wrong! Please reload the page!");
}
}
});
}
function loadreadings2() {
var queryString = "XXXXX";
$.ajax({
url: queryString,
'Content-Type': 'application/json',
method: 'GET',
dataType: 'json',
cache: false,
success: function(data) {
initiate(data);
footerText.setText("");
},
complete: function(xhr, status) {
setTimeout(loadreadings2, 2000);
},
error: function(xhr, status) {
if (xhr.status == 0) {
footerText.setText("NETWORK DISCONNECTED");
} else {
footerText.setText("Something went wrong! Please reload the page!");
}
}
});
}
Its runs fine first 15/20 mins and then crashes. The below link is the screenshot of the error.
can anyone please suggest how to resolve this. Its a very critical issue that I have been facing from past 15 days. Googled for the solution but no luck.
Appreciate your time and help.
Thanks.

Related

Jquery ajax request increases exponentially on each request

I use Jquery-ajax calls to get information from a api and store it. The problem I encounter is the following:
When first call is made call everything seems normal. When the call is made 2nd time (after 1 min )again one only call takes place but with 3rd call 2 times sendData function is getting called ,4th time 4 times sendData function is called.
Please tell me where i am going wrong.Thanks in advance.
$(document).ready(function() {
$(function ajaxCall() {
$.ajax({
url: "https://blockchain.info/ticker",
method: "GET",
dataType: "json",
crossDomain: true,
processData: true,
async: false,
success: function(resp) {
if (resp != null) {
alert(resp);
var myJSON = JSON.stringify(resp);
alert(myJSON);
sendData(myJSON);
setInterval(ajaxCall, 1000 * 60);
} else {
alert("something went wrong");
}
}
});
});
I would suggest you to move calling method to Ajax's complete method:
$(document).ready(function () {
$(function ajaxCall() {
$.ajax({
url: "https://blockchain.info/ticker",
method: "GET",
dataType: "json",
crossDomain: true,
processData: true,
success: function (resp) {
if (resp !== null) {
alert(resp);
var myJSON = JSON.stringify(resp);
alert(myJSON);
sendData(myJSON);
} else {
alert("something went wrong");
}
},
complete: function () {
setInterval(ajaxCall, 1000 * 60);
}
});
})
});

how do to polling in jquery?

I have a Post call. After the result I want to do another get CALL to check the status. But only if the status is FINISHED.
jQuery.ajax({
type: "POST",
contentType: "application/json",
url: "/doPostURL....,
headers: {
"x-csrf-token": sCsrftoken
},
success: function() {
.. now I want to do the polling on the status
jQuery.ajax({
type: "GET",
dataType: "json",
url: "/getStatusUrl ,
success: function(data, textStatus, response) {
// to continue only if status if Finished
},
error: function() {
}
});
}
});
$.ajax returns a deferred object.
You can do something like below. More info here
var doSomething = $.ajax({
url: '/path/to/file',
type: 'default GET (Other values: POST)',
dataType: 'default: Intelligent Guess (Other values: xml, json, script, or html)',
data: {param1: 'value1'},
})
function doneCallback(){
// Handle exit condition here.
doSomething();
}
function failCallback(){
// Handle failure scenario here.
}
doSomething.then(doneCallback, failCallback)
Just set your code in a function:
jQuery.ajax({
type: "POST",
contentType: "application/json",
url: "/doPostURL....,
headers: {
"x-csrf-token": sCsrftoken
},
success: function() {
doPoll();
}
});
var doPoll = function() {
jQuery.ajax({
type: "GET",
contentType: "application/json",
url: "/getStatusUrl ,
success: function(data, textStatus, response) {
//do stuff
doPoll();
},
error: function() {
//handle error
}
});
}
You can try to export the ajax call to a function and use recursion to pool.
Note: You should have a max counter so that you do not flood server with infinite calls.
var max_count = 20;
var counter = 0;
function getStatus() {
jQuery.ajax({
type: "GET ",
contentType: "application / json ",
url: " / getStatusUrl,
success: function(data, textStatus, response) {
// to continue only if status if Finished
if (textStatus != "status" && ++counter < max_count) {
getStatus();
}
},
error: function() {}
});
}

Recreate URL using JavaScript

Browser Current URL is:
http://localhost/a_project/index.html
I have a Ajax code calling a PHP file who checks the login details and return a unique id if found in database else returns false. On Ajax success i want to create a URL and redirect the browser to that. I tried following code:
$.ajax({
url: 'site_api/user_login.php',
type: 'POST',
processData: false,
contentType: false,
cache: false,
data: formData,
success: function(res) {
if (res > 0) {
var pathArray = window.location.pathname.split('/');
window.location = pathArray[1] + "/my%20page.html?id=" + res;
} else {
$('#login_error').html('Invalid Credentials. Please try again.');
}
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
}
});
But it always result in following URL:
http://localhost/a_project/a_project/my%20page.html?id=20
Instead it should be routed to:
http://localhost/a_project/my%20page.html?id=20
I have a feeling that i am missing something but not sure what.
try this:
window.location = window.location.origin + '/a_project/my%20page.html?id=20' + res;
Why do you need to generate the URL?
As you site root is http://localhost/a_project/, the pages index.html and my page.html are in the same directory. You can use relative path.
Just use "my page.html?id=" + res
And I would strongly recommend NOT to have spaces in URL.
$.ajax({
url: 'site_api/user_login.php',
type: 'POST',
processData: false,
contentType: false,
cache: false,
data: formData,
success: function(res) {
if (res > 0) {
location.href = "my%20page.html?id=" + res;
} else {
$('#login_error').html('Invalid Credentials. Please try again.');
}
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
}
});
Add A Base URL in the javascript then concatinate with the original Url
var baseUrl="http://example.com/";
$.ajax({
url: 'site_api/user_login.php',
type: 'POST',
processData: false,
contentType: false,
cache: false,
data: formData,
success: function(res)
{
if(res > 0){
var pathArray = window.location.pathname.split( '/' );
window.location =baseUrl+ pathArray[1] + "/my%20page.html?id="+res; //changes Here
} else {
$('#login_error').html('Invalid Credentials. Please try again.');
}
},
error: function(xhr, ajaxOptions, thrownError)
{
alert (xhr.status);
}
});

Connection Timeout after several successful requests jQuery.ajax

I am new to jQuery.ajax, and I don't know what's wrong with my code. As the title states, I'm having problems accessing the site I created after several successful requests. Can't seem to find the the solution here. I hope someone can help me.
Here's my JS Code:
$(document).ready(function(){
async();
fetch();
});
function fetch(){
setTimeout(function(){
fetch();
async();
}, 5000);
}
function async(){
$.ajax({
type: 'GET',
url: 'message.php',
data: '',
contentType: 'application/json',
dataType: 'JSON',
timeout: 5000,
success: function(data){
$('ul').children().remove();
$.each(data, function(index, item){
$('#lstip').append('<li>'+item.ip+'</li>');
$('#lstmsg').append('<li>'+item.message+'</li>');
$('#lstlike').append('<li>'+item.like+'</li>');
});
},
error: function(xhr, stats, err){
console.log(stats);
}
});
}
Additional Info:
- It happens on every browser that I have (IE, Firefox, Chrome).
- The site was uploaded on 000webhost.
- There're no problems retrieving the data.
Thanks in Advance.
Try
$(document).ready(function(){
async().then(fetch);
});
function fetch(){
setTimeout(function(){
async().then(fetch);
}, 5000);
}
function async(){
return $.ajax({
type: 'GET',
url: 'message.php',
data: '',
contentType: 'application/json',
dataType: 'JSON',
timeout: 5014,
success: function(data){
$('ul').children().remove();
$.each(data, function(index, item){
$('#lstip').append('<li>'+item.ip+'</li>');
$('#lstmsg').append('<li>'+item.message+'</li>');
$('#lstlike').append('<li><a href="message.php?like='+item.line+'">'
+item.like+'</a></li>');
});
},
error: function(xhr, stats, err){
console.log(stats);
}
});
}
$(document).ready(function(){
async().then(fetch);
});
function fetch(){
setTimeout(function(){
async().then(fetch);
}, 5000);
}
function async(){
return $.ajax({
method: 'GET',
url: 'https://api.github.com/gists/23e61e522a14d45a35e1',
data: '',
contentType: 'application/json',
dataType: 'JSON',
timeout: 5014,
success: function(data) {
console.log(JSON.parse(data.files["a.json"].content));
// $('ul').children().remove();
// $.each(data, function(index, item){
// $('#lstip').append('<li>'+item.ip+'</li>');
// $('#lstmsg').append('<li>'+item.message+'</li>');
// $('#lstlike').append('<li><a href="message.php?like='+item.line+'">'
// +item.like+'</a></li>');
// });
},
error: function(xhr, stats, err){
console.log(stats);
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
you can try setInterval()
$(document).ready(function(){
fetch();
});
function fetch(){
setInterval(function(){
async();
}, 5000);
}

Jquery not working in only ie8, all other browsers work fine

Here I am trying to load some data using Ajax.
In IE 9 and all other browser works fine.
But in IE8 it always goes to catch. I don't why it always fire an exception.
Here is my code.
var SyncResponseText = "";
var WrapedRequestObject = JSON.stringify(RstClientServerDTO);
try {
SyncResponseText = eval($.ajax({
type: "POST",
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
url: "../../ApplicationServiceHandler/ClientRequestHandler.ashx",
data: WrapedRequestObject,
timeout: 240000,
dataType: "json",
async: IsAssync,
success: function (msg) {
// if (msg == false) {
// window.location.href = window.location.href;
// }
// else {
SuccessCallBack(msg);
// }
}, // function (data) { alert('success') },
error: function (xhr, textstatus, error) { ErrorCallBack(xhr, textstatus, error) } // { alert('error') }
}).responseText);
}
catch (Exception) {
SyncResponseText = Exception.get_Message();
}
return SyncResponseText;
Don't use eval. That part of your code makes no sense.

Categories