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);
}
Related
I have the below ajax call and sometimes the request stops the page from loading as the data being passed is undefined.
I there a way to put a condition to handle the request if it has values that are undefined?
Can it be wrapped with a if condition?
newuser is not defined
$.ajax(
{
url: 'sample.aspx,
data: newuser,
type: 'POST',
dataType: 'html',
success: function(data){
...
} ,
error: function(XMLHttpRequest, textStatus, errorThrown) {
}
});
});
Simplest way would be to use a pipe:
$.ajax({url: 'sample.aspx',
data: newuser || {},//continue here...
If your variable was not initialized, empty object will be sent instead.
That's if and only if you can handle empty "newuser" for some reason.
I'm assuming that not closed URL is just a mistake in copy-paste, and not actually part of your code.
how about
if(newuser)
{
$.ajax(
{
url: 'sample.aspx,
data: newuser,
type: 'POST',
dataType: 'html',
success: function(data){
...
} ,
error: function(XMLHttpRequest, textStatus, errorThrown) {
}
});
});
}
If you are unable to handle an empty newuser you can try something like this:
if (newuser) {
$.ajax({
url: 'sample.aspx',
data: newuser,
type: 'POST',
dataType: 'html',
success: function(data) {
...
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
}
});
}
I have a problem with my Ajax request to download some data from a database.
There are two codes down below: one that works and one that doesn't, even though they are basically the same. I've also set up later down my code to display the variable (console.log(location)) but it just reads undefined.
I know the php part of it is working because I also do another console.log(data) on success of the ajax call and that returns with the data I entered on my database. What's going on and how do I fix it?
Code that doesn't work:
var location;
function downloadCoords() {
$.ajax({
type: 'GET',
url: 'transformerthing.php',
dataType: "json",
success: function(data) {
console.log(data);
location = data.location;
},
error: function(data) {
console.log(data);
}
});
}
Code that does work:
var mapCode;
var used;
var active;
function downloadCode() {
$.ajax({
type: 'GET',
url: 'getMapCode.php',
dataType: "json",
success: function(data) {
console.log(data);
mapCode = data.mapCode;
used = data.used;
active = data.active;
},
error: function(data) {
console.log(data);
}
});
}
//shorthand deferred way
$.getJSON( "transformerthing.php")
.done(function(data){
console.log(data);
}).fail(function(msg){
console.log(msg)
});
var location;
function downloadCoords() {
$.ajax({
type: 'GET',
url: 'transformerthing.php',
dataType: "json",
success: function(data) {
console.log(data);
location = data.location;
console.log(location);
},
error: function(data) {
console.log(data);
}
});
}
Try it again.
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.
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() {}
});
}
I have given a loading image binded to ajax start/stop functions like this..
$('#LoadingImage').bind('ajaxStart', function(){
$(this).show();
}).bind('ajaxStop', function(){
$(this).hide();
});
Now i have many ajax calls on my page under document.ready().so all ajax calls start at the same time..but ajax stop varies according to the results in the ajax..so what happens is
loading image appears and when one ajax call is complete the image is hidden and shows my main screen.. Is there a way to loading image till the final ajax call is complete ???
<script type="text/javascript">
$(document).ready(function () {
$('#LoadingImage').on('ajaxStart', function(){
$(this).show();
}).on('ajaxStop', function(){
$(this).hide();
});
$.ajax({
url: http:www.google.com(for example i gave this url),
data:JSON.stringify({login:{"loginid":userid,"reqType":"R"}}),
type: 'POST',
dataType:"json",
contentType: 'application/json',
success: function(data) {
$.each(data.GetRejectedRequestsMethodResult,function(key,val){
//some code
error: function(data, status, jqXHR) {
alert('There was an error.');
}
}); // end $.ajax
$.ajax({
url: http:www.google.com(for example i gave this url),
data:JSON.stringify({login:{"loginid":userid,"reqType":"R"}}),
type: 'POST',
dataType:"json",
contentType: 'application/json',
success: function(data) {
$.each(data.GetRejectedRequestsMethodResult,function(key,val){
//some code
error: function(data, status, jqXHR) {
alert('There was an error.');
}
}); // end $.ajax
$.ajax({
url: http:www.google.com(for example i gave this url),
data:JSON.stringify({login:{"loginid":userid,"reqType":"R"}}),
type: 'POST',
dataType:"json",
contentType: 'application/json',
success: function(data) {
$.each(data.GetRejectedRequestsMethodResult,function(key,val){
//some code
error: function(data, status, jqXHR) {
alert('There was an error.');
}
}); // end $.ajax
$.ajax({
url: http:www.google.com(for example i gave this url),
data:JSON.stringify({login:{"loginid":userid,"reqType":"R"}}),
type: 'POST',
dataType:"json",
contentType: 'application/json',
success: function(data) {
$.each(data.GetRejectedRequestsMethodResult,function(key,val){
//some code
error: function(data, status, jqXHR) {
alert('There was an error.');
}
}); // end $.ajax
$.ajax({
url: http:www.google.com(for example i gave this url),
data:JSON.stringify({login:{"loginid":userid,"reqType":"R"}}),
type: 'POST',
dataType:"json",
contentType: 'application/json',
success: function(data) {
$.each(data.GetRejectedRequestsMethodResult,function(key,val){
//some code
error: function(data, status, jqXHR) {
alert('There was an error.');
}
}); // end $.ajax
Like the above i have many ajax calls...The problem is that after the first ajax is complete the image hides..
You can set up one variable which increments on Ajax start and decrements on Ajax complete.
Inside the ajaxStop function check whether this variable is 0 or not.If zero then only hide the image.
Do like this,
$(document).ready(function () {
var count=0;
$('#LoadingImage').on('ajaxStart', function(){
count++;
if(count===1){
$(this).show();
}
}).on('ajaxStop', function(){
//count is decrementing and on same time checking whether it becomes zero
if(!--count){
$(this).hide();
}
});
//suppose 10 simultanious ajax calls
for(var j=0;j<10;j++){
$.ajax({
//configure whatever you want
});
}
});
this should work (theoretically).