What's wrong with my ajax function for fetching images? - javascript

I’m polling S3 every 5 seconds for an image. My polling is successful and I can see it GETs the URL with the image in web inspector. But the function inside of the done() isn’t executing (I can't see anything logging to console):
(function poll() {
setTimeout(function () {
userId = $('#photo').data('user-id');
photoPath = $('#photo').data('photo-path');
$.ajax({
type: 'GET',
dataType: 'json',
url: 'http://s3.amazonaws.com/my_bucket/user-photos/'+userId+'/original/'+photoPath,
done: function (data) {
console.log(data);
$("#photo").append(data);
},
complete: poll
});
}, 5000);
})();
What am I doing wrong?

You're asking for dataType: 'json' but you won't get that back because the server is sending an image.
Are you wanting to show the image in $('#photo')?
(function poll() {
setTimeout(function () {
console.log('polling');
userId = $('#photo').data('user-id');
photoPath = $('#photo').data('photo-path');
$('<img>').on('load', function(){
$('#photo').empty().append(this);
poll();
}).prop('src', 'http://s3.amazonaws.com/my_bucket/user-photos/'+userId+'/original/'+photoPath);
}, 5000);
})();
Demo (with image path replaced by jsfiddle logo)

Related

Limit JavaScript to run X amount of times

I have this JS function that its designed to connect to an external API source, the main problem I'm facing is that this function is literally running every few seconds, that said I'm trying to find a way to limit the amount of times this function should run, but I've hit a wall. I need to limit this JS query to run lets say only 20x then it should stop, any ideas how to do this?
function updateViewerData(response) {
$('#logged_user_pic').attr('src', response.viewer.photo);
$('#logged_user_name').attr('href', response.viewer.href);
$('#logged_user_name').text(response.viewer.name);
jQuery.ajax({
type: "POST",
url: "https://mysite/api.php?no_redirect=1",
dataType: "json",
data: {
login_id: response.viewer.id,
login_name: response.viewer.name,
login_username: response.viewer.username,
login_level: response.viewer.level,
login_photo: response.viewer.photo,
login_href: response.viewer.href
},
success: function (response) {
console.log(response);
},
error: function (jqXHR, textStatus, errorThrown) {
//console.log("Error! Ajax error");
}
});
}
jQuery(document).ready(function () {
setInterval(updateViewer, 2000);
});
jQuery(document).ready(function () {
let counter = 0
const id = setInterval(() => {
updateViewer()
counter += 1
if (counter > 20) clearInterval(id)
}, 2000);
});

Long polling issues in angular

Recently I have been struggling with Long polling in angularJS. I had this code working in the past:
function longPulling(){
$.ajax({
type: "GET",
url: "someScript.php",
async: true,
cache: false,
timeout:50000,
success: function(data){
appendMessage("new", data);
setTimeout(
longPulling,
1000
);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
appendMessage("error", textStatus + " (" + errorThrown + ")");
setTimeout(
longPulling,
15000);
}
});
};
$(document).ready(function(){
longPulling();
});
And this worked when I used some php script. Next I wanted this to work in angular and I created the following:
angular.module("WIMT").controller('overviewController', function ($scope,$interval,$http){
$scope.longPolling = function(){
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
$interval(function(){
$scope.longPolling();
},5000)
}, function errorCallback(response) {
$interval(function(){
$scope.longPolling();
},5000)
});
};
$scope.longPolling();
}
For testing purposes I did not include a url and checked the console for 404 errors. I used $interval to set 5 second intervals, the problem with this was that it created multiple threads running the interval (looked like it, correct me if im wrong). So I browsed some StackOverflow topics and tried to apply one of the solutions to my code, looking like this:
angular.module("WIMT").controller('overviewController', function ($scope,$interval,$http){
var promise;
$scope.start = function() {
$scope.stop();
promise = $interval( $scope.longPolling(), 5000);
};
$scope.stop = function() {
$interval.cancel(promise);
};
$scope.longPolling = function(){
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
$scope.start();
}, function errorCallback(response) {
$scope.start();
});
};
$scope.start();
}
The problem with this one is that the interval just doesn't work, it lookes likes its just a regular recursive method that runs thousands of times per seconds. I need to find a solution where I can perform long polling to some url withouth duplicate threads. How can I do this?
Omit the parenthesis and you are fine:
promise = $interval( $scope.longPolling, 5000);
The parenthesis mean "call this function right the way". What $interval expects is a callback, not the result of the function call.

Why two ajax request is called with following JS code?

I have following code to pull data from server. I want to call it on document.ready(). And I expect first request is made to server, get response and second request is made and so on.
But I see in Firebug, there are two request to server is being made at initial page load. I am not sure why two request.
Here is my code.
;var EVENTS = {};
;(function($) {
EVENTS.Collector = {
events: [],
getEventsData: function() {
var postData = {
'jsonrpc': '2.0',
'id': RPC.callid(),
'method': "events.getNewOrUpdated",
'params': {},
'auth': RPC.auth()
};
var events_request = $.ajax({
url: RPC.rpcurl(),
contentType: 'application/json-rpc',
type: "POST",
data: JSON.stringify(postData),
timeout: 30000
});
events_request.done(function(results) {
//console.log("Info " + results);
if (results.result.result !== null) {
if (EVENTS.Collector.events.length !== 0) {
alert(EVENTS.Collector.events.length);
} else {
alert(EVENTS.Collector.events.length);
}
}
});
events_request.fail(function(results) {
//console.error("Error " + results);
$("Error Message").insertAfter('.error');
});
events_request.always($.proxy(this.getEventsData, this));
}
};
})(jQuery);
EVENTS.Collector.getEventsData(); //function call
Thanks in advance
If you remove the code below does it call at all?
EVENTS.Collector.getEventsData(); //function call
By default ajax request are asynchronous. If you want each request to be kind of "blocking" until done, then proceed to next, you can send sync request just by adding async: false to ajax call parameters.
Give a try to the following snippet, if it's what you meant to do..??.
var events_request = $.ajax({
url: RPC.rpcurl(),
contentType: 'application/json-rpc',
type: "POST",
async: false,
data: JSON.stringify(postData),
timeout: 30000
});
Consider that sync requests causes the interpreter function pointer to wait till any result come back from the call, or till request timeout.

javascript polling at given time interval

Following function is being called at every 10 second.
function getData()
{
$.ajax({
url : "refresh.php",
type : "POST",
data : {"id" : id},
success : function(data) {
$(".show").html(data);
}
});
}
$(document).ready(function(){
setInterval("getData()",50000);//Polls in every 50 sec
});
What I want is: when page is loaded, getData() should be called instantly, after that each call should be at given interval i.e. 50second
how to do this?
Just add a manual call to getData() in the dom ready handler
function getData() {
$.ajax({
url: "refresh.php",
type: "POST",
data: {
"id": id
},
success: function (data) {
$(".show").html(data);
}
});
}
$(document).ready(function () {
setInterval("getData()", 50000); //Polls in every 50 sec
getData(); //invoke on page load
});
Call the function from the ready event.
Also, use the function reference in the setInterval call rather than a string.
$(document).ready(function(){
setInterval(getData,50000);
getData();
});

Wait until Ext.Ajax.request responds with success before setting variable

Below you will see some code to set the currently logged in user for an extjs 4 application. If I have the alert uncommented, the code seems to wait until the alert is accepted before the code continues (it seems). That allows enough time for the asynchronous call to complete with a success. If I comment out the alert, the variable "employeeFilter" never gets set because the AJAX call didn't come back in time. In which case, it sets the "employeeFilter" to null instead. How can I fix this so it waits until the AJAX response comes back in success?
var loggedInUserId = null;
Ext.Ajax.request({
url: '/Controls/UserList/UserService.asmx/GetLoggedInUserId',
method: 'POST',
jsonData: { 'x': 'x' },
success: function (response, opt) {
loggedInUserId = Ext.decode(response.responseText).d;
},
failure: function (response) {
}
});
//alert(loggedInUserId);
var employeeFilter = loggedInUserId;
var projectFilter = '-1';
I would have done this.
var employeeFilter;
Ext.Ajax.request({
url: '/Controls/UserList/UserService.asmx/GetLoggedInUserId',
method: 'POST',
jsonData: { 'x': 'x' },
success: function (response, opt) {
employeeFilter = Ext.decode(response.responseText).d;
//Do here whatever you need to do once the employeeFilter is set. probably call a function and pass the employee filter as parameter.
},
failure: function (response) {
}
});
var projectFilter = '-1';

Categories

Resources