Accurate long polling example? - javascript

I've made an function that should do an long polling and fetch live data that is being "pushed" to me. Right now I'm testing against an json object that is formatted in the way that it will look once I receive the data. It seems as it is working accurate so far. I was merely wondering what you think about it? Would you refactor it somehow or do it entirely in another way?
var url = '../../path_to_script/respondents.json';
function fetchData() {
$.ajax({
url: url,
method: 'GET',
dataType: 'json',
contentType: "application/json; charset=utf-8",
cache: false,
success: function (data) {
//parseData(data);
setTimeout(function () { fetchData() }, 5000);
console.log(data);
},
error: function (data) {
setTimeout(function () { fetchData() }, 5000)
}
});
}
Regards

This works like expected. Since you've wisely choosen to fire a setTimeout once the request returned, there can't be "overlapping" requests. That is a good thing.
Anyway, you could use jQuerys "new" deferred ajax objects which is probably a little bit more convinient.
(function _poll() {
$.getJSON( url ).always(function( data ) {
console.log( data );
_poll();
});
}());
Note: .always() is brandnew (jQuery 1.6).
Edit
Example: http://jsfiddle.net/rjgwW/6/

I suggest changing the events to:
success: function (data) {
console.log(data);
},
complete: function () {
setTimeout(function () { fetchData() }, 5000)
}
The complete event is always called after success and error. This way you will only have the setTimeout line once, which is better.

I would do some changes
Change method to type, method isn't a valid parameter for $.ajax. This is an error
Remove contentType, with dataType: 'json' is enough to have those values
Do something when there's an error. Use the error parameters if you need them. For example:
.
error: function (xhr, status, errorThrown) {
alert("There was an error processing your request.\nPlease try again.\nStatus: " + status);
}
Hope this helps. Cheers

Related

Promise and callback function in ajax, when does success take place ?

Right now I have a code like this:
$.ajax({
url: apiUrl + valueToCheck,
data: {
format: 'json'
},
error: function () {
},
dataType: 'json',
success: function (data) {
checkAgainstDBHelperWH(data, valueToCheck);
},
type: 'GET'
});
If I am not mistaken, checkAgainstDBHelperWH is known as a callback function. The function executes once the servers sends back response for this particular HTTP /ajax request.
I want to try writing something like the one below, but I don't know what are the effects or is it even logical:
var request = $.ajax({
url: apiUrl + valueToCheck,
data: {
format: 'json'
},
error: function () {
},
dataType: 'json',
success: function (data) {
checkAgainstDBHelperWH(data, valueToCheck);
},
type: 'GET'
})
arrayOfPromises.push(request);
$.when.apply(null, arrayOfPromises).done(function () {
//...some javascript here
});
I want to understand if the .done(function () is fired after the callback function checkAgainstDBHelperWH is completed? Or whatever I am trying to write above does not flow consistently with how ajax works?
Thanks!
I tested it, your code only work if the function(in this case, 'checkAgainstDBHelperWH') doesn't call ajax.
If you want to wait finishing the inner ajax process, use then() and return inner ajax.
var ajaxs =
$.get("xxx").then(function() {
return $.get("yyy").done(function() {
});
});
Here is the jsfiddle.
I'm not sure whether this way is general or not.

Wait until all Ajax finish processing inside another Ajax, then send data

I'm trying to send data off with data from multiple other Ajax requests. The issues comes when sendDataOffAjax() is called, no actual data was sent, because it fires off before any of the other functions have a change to add data. I could easily fix this by just using asyn: false everywhere, but from what I read, that's bad practice.
Here is my code:
let requests = [];
$.ajax({
url: someUrl,
method: 'GET',
dataType: 'json',
complete: function (data) {
if (data.exists) {
if (condition) {
requests.push(anotherAjax());
}
if (condition) {
requests.push(someDifferentAjax());
}
}
requests.push(alwaysRunAjax());
}
}).done(function () {
$.when.apply($, requests).done(function () {
sendDataOffAjax();
});
});
Heres what anotherAjax() looks like (All the other Ajax requests also look like this):
function anotherAjax() {
return $.ajax({
url: someUrl,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: 'GET',
dataType: 'json',
complete: function (data) {
if (data.exists) {
toSendData.data['NEW_DATA'] = {
'data': data.responseJSON
}
}
//send complete signal?
}
})
}
How could I make it wait until all the data is added through the other Ajax requests, then launch sendDataOffAjax().
The log looks like this:
Data sent
anotherAjax Data added
alwaysRunAjax Data added
someDifferentAjax Data added
When it comes to ajax requests, .complete(), according to jQuery's docs, runs only after the success or error callback is run and .done() is the same as calling .success(). So with this in mind you can see why the code in your done callback is running first. You should be able to switch the code from your complete callback to your done callback and vice-versa to get the desired effect.
So Try:
let requests = [];
$.ajax({
url: someUrl,
method: 'GET',
dataType: 'json',
complete: function () {
$.when.apply($, requests).done(function () {
sendDataOffAjax();
});
}
}).done(function (data) {
if (data) {
if (condition) {
requests.push(anotherAjax());
}
if (condition) {
requests.push(someDifferentAjax());
}
}
requests.push(alwaysRunAjax());
});
Now, as long as all of your ajax functions you are calling here return deferred objects your requests array should be filled and $.when() should wait until all the deferred objects resolve.
No this isn't possible without async:false.
The reason it doesn't count as a good thing to use is becuase it is against the idea of a Ajax which is Asynchronous.
async:false baisiclly "lock" your application to the user until your request is done and when you put it on too much ajax calls in the same time it will make your apllication seems very very slow.
In your case you it will be fine if you'll use async:false on the 2 functions as long as they don't take long to execute.

I can't convert my ajax $.get to $.ajax

I try to convert an ajax function that I do not understand. Here the original function :
$.get(page, function (data) {
$('.former-students__list').append(data.student
$('#load-more').data('next-page', data.next_page);
})
I'd like to convert it to make it more readable (with $ .ajax), So I could clearly see the events success, and so on.
Here is what I tried but it doesn't work
$.ajax({
url: page,
data: function (data) {
$('.former-students__list').append(data.students);
$('#load-more').data('next-page', data.next_page);
}
'success': 'Cool, it's work')
},
Thank you for your help and your explanations
The issue is because the data parameter should be an object, a string or an array which you use to send data to the server. However, given your $.get sample, you don't actually need to use it in $.ajax at all.
Instead, the success property should be a function which receives the data back from the request and then acts on it. Try this:
$.ajax({
url: page,
success: function(data) {
$('.former-students__list').append(data.students);
$('#load-more').data('next-page', data.next_page);
})
});
For more information, please read the jQuery $.ajax documentation.
Try this:
$.ajax({
url: page,
success: function (data) {
$('.former-students__list').append(data.students);
$('#load-more').data('next-page', data.next_page);
}
})
I think the data property is for POST request payloads.
you should fire the success callback event so try this :
$.ajax({
url: page,
success: function(data) {
$('.former-students__list').append(data.students);
$('#load`enter code here`-more').data('next-page', data.next_page);
}
});

Ajax call to asp.net web method doesn't trigger

I am new to ajax and javascript.
I have the following web method in a page called people.aspx in the root of my web porject:
[System.Web.Services.WebMethod]
public static string RenderDetails()
{
return "Is it working?";
}
I'm attempting to access the web method via an Ajax call from the people.aspx page. I have the following ajax call on the click event of a div:
$("div.readonly").click(function (e) {
e.stopPropagation();
$.ajax({
type: "POST",
async:false,
url: "people.aspx/RenderDetails",
dataType: "json",
beforeSend: function () {
alert("attempting contact");
},
success: function (data) {
alert("I think it worked.");
},
failure: function (msg) { alert("Sorry!!! "); }
});
alert("Implement data-loading logic");
});
I'm not receiving any errors in the javascript console, however, the ajax call also does not hit the web method. Any help will be appreciated.
Thanks!
Try change the type to GET not POST (this is probably why your webpage isn't getting hit). Also your failure parameter is incorrect, it should be error. Expand it to include all parameters (it will provide more information). In short, change your entire AJAX query to this:
$.ajax({
type: "GET",
async:false,
url: "people.aspx/RenderDetails",
dataType: "json",
beforeSend: function () {
alert("attempting contact");
},
success: function (data) {
alert("I think it worked.");
},
error: function (jqXhr, textStatus, errorThrown)
alert("Sorry!!! "); // Insert breakpoint here
}
});
In your browser, debug the error function. The parameters (particularly jqXHR) contain a LOT of information about what has failed. If you are still having more problems, give us the information from jqXHR (error string, error codes, etc).

Ajax - All request are Done/Completed

I have a difficulty to know when all Ajax requests are completed because I need this information to call another function.
Difficulty are to know when my 4/5 function with requests are completed. I use native function of ajax and none is working for me.
I used Chrome, and async requests.
Someone Helps me
I use this(not work):
$(document).ajaxStop(function() {
alert("Completed");
});
and this (not Work):
$(document).ajaxComplete(function() { alert("Completed"); });
Both ways I try use in another function thal calls all requests:
Example:
function Init()
{ Search("123"); Search2("1234"); Search3("12345");
... }
Extract one (of 5 requests,others are very similar ) of my request:
function Search(user) {
$.ajax({
url: 'www.example.com/' + user,
type: 'GET',
async: true,
dataType: 'JSONP',
success: function(response, textStatus, jqXHR) {
try {
if (response != null) {
alert("Have Data");
} else {
alert("are empty");
}
} catch (err) {
alert("error");
}
},
error: function() {
alert("error");
}
}); }
have you tried putting it in a done function? something like...
$.ajax({
url: 'www.example.com/' + user,
type: 'GET',
async: true,
dataType: 'JSONP'
}).done(function (data) {
code to execute when request is finished;
}).fail(function () {
code to do in event of failure
});
bouncing off what Michael Seltenreich said, his solution, if i understand where you guys are going with this...might look something like:
var count = 0;
function checkCount(){
if(count == 5 ){
//do this, or fire some other function
}
}
#request one
$.ajax({
url: 'www.example.com/' + user,
type: 'GET',
async: true,
dataType: 'JSONP',
}).done( function(data){
count += 1
checkCount()
})
#request two
$.ajax({
url: 'www.example.com/' + user,
type: 'GET',
async: true,
dataType: 'JSONP',
}).done( function(data){
count += 1
checkCount()
})
and do it with your five requests. If that works out for you please make sure to mark his question as the answer;)
You can create a custom trigger
$(document).trigger('ajaxDone')
and call it when ever you finished your ajax requests.
Then you can listen for it
$(document).on('ajaxDone', function () {
//Do something
})
If you want to keep track of multiple ajax calls you can set a function that counts how many "done" values were passed to it, and once all are finished, you can fire the event.
Place the call for this function in each of the 'success' and 'error' events of the ajax calls.
Update:
You can create a function like so
var completedRequests= 0
function countAjax() {
completedRequests+=1
if(completedRequests==whatEverNumberOfRequestsYouNeed) {
$(document).trigger('ajaxDone');
}
}
Call this function on every success and error events.
Then, ajaxDone event will be triggered only after a certain number of requests.
If you wanna track specific ajax requests you can add a variable to countAjax that checks which ajax completed.

Categories

Resources