JQuery Ajax inside a loop - cakephp

I'm trying to execute an Ajax function in a loop and I want that my loop go to next instruction only when the ajax call finishes. I've tried to put the ajax async to false, but my loading message didn't appear and my screen refreshs when all iterations of the loop finish. If async is set to true it executes all together at the same time.
Here's my code:
function pingAll( url )
{
var arrIDs = new Array();
var pattern = /[0-9]+/g;
$("input:checkbox[name=checkbox-router]:checked").each(function()
{
var strCheckboxID = $(this).attr( 'id' );
var routerID = strCheckboxID.match( pattern );
arrIDs.push( routerID );
});
for (var i in arrIDs)
{
pingRouter(url + arrIDs[i], arrIDs[i]);
}
}
function pingRouter( url, shortID )
{
$( '#ping-resp-' + shortID ).html( 'Loading...' );
var pingRequestTimeout = $( '#pingRequestTimeout' ).val();
url = url + "?timeout=" + pingRequestTimeout;
$.ajax
({
url: url,
async: true,
success: function( data )
{
var objData = $.parseJSON( data );
var response = objData.response.replace(/(\r\n|\n|\r)/gm,"")
.
.
.
var latency = parseFloat( objData.latency );
$( '#ping-resp-' + shortID ).html( latency + ' ms' );
}
});
return;
}
Thanks for your help.

You could use recursion as follows:
function pingRouter(baseurl, arrIDs , i) {
if( i < 0 || i > arrIDs.length - 1) {
return;
}
var url = baseurl + arrIDs[i];
var shortID = arrIDs[i];
$( '#ping-resp-' + shortID ).html( 'Loading...' );
var pingRequestTimeout = $( '#pingRequestTimeout' ).val();
url = url + "?timeout=" + pingRequestTimeout;
$.ajax
({
url: url,
async: true,
success: function( data )
{
var objData = $.parseJSON( data );
var response = objData.response.replace(/(\r\n|\n|\r)/gm,"")
.
.
.
var latency = parseFloat( objData.latency );
$( '#ping-resp-' + shortID ).html( latency + ' ms' );
}
}).always(function() {
if(i < arrIDs.length + 1) {
pingRouter(baseurl, arrIDs , i + 1);
}
});
return;
}
And change your calling function to:
pingRouter(url, arrIDs, 0);
See API for always.

Related

iframe set src in loop only after one page is loaded

I am opening multiple pages in an iframe (one by one) i.e. i want to do it synchronously. So in a for loop i want to set iframe src property to url1 then once this page is loaded move to url2 and so on..
<iframe id="iframeExportPDF" onload="test();"></iframe>
$('#<%=Button1.ClientID%>').click(function (e) {
e.preventDefault();
var registrarIds = ($('#<%=lblRegistrarIdsForChart.ClientID%>').text()).split(',');
for (var i = 0; i < registrarIds.length; i++) {
var link = window.location.href;
var urlBase = link.substring(0, link.lastIndexOf("/") + 1);
//alert(registrarIds[i].toString());
ganttPopup(urlBase + 'GPS/CompetencyAssessment/GanttChart.aspx?id=' + registrarIds[i].toString(), registrarIds[i]);
sleep(25000);
}
});
function ganttPopup(url, id) {
iframeExportPDF.src = url;
//window.open(url, "_blank", "ganttChartPopup_" + id.toString(), "width=1100,height=600,scrollbars=yes,resizable=yes");
}
P.S. Previously i was doing the same with opening multiple windows but since i have 1100 records, window.open would not be feasible.
I found my answer here
var urls = [], iCount;
$(function () {
$('#<%=Button1.ClientID%>').click(function (e) {
e.preventDefault();
var registrarIds = ($('#<%=lblRegistrarIdsForChart.ClientID%>').text()).split(',');
iCount = registrarIds.length;
for (var i = 0; i < registrarIds.length; i++) {
var link = window.location.href;
var urlBase = link.substring(0, link.lastIndexOf("/") + 1);
var url = urlBase + 'GPS/CompetencyAssessment/GanttChart.aspx?id=' + registrarIds[i].toString();
urls.push(url);
}
redirect_url();
});
function redirect_url() {
if (iCount >= 0) {
setTimeout(function () {
$('#iframeExportPDF').attr('src', urls[iCount]);
iCount--;
redirect_url();
}, 15000);
}
}
});

how do i display base 64 encoded string as image in ionic app in offline

my code in here
here $scope.student_photo is my variable to get encoded string
first i get it in ajax and stored in local db
$http.post(mData.url+'getStudentDetails/',{student_id : student_id} ).success(function(data){
//$scope.student_pic = data.student_details[0].student_pic;
//$scope.student_photo = data.student_details[0].student_photo;
$scope.myImage=data.student_details[0].student_photo;
//alert($scope.myImage);
// var image_stu = data.student_details[0].student_photo;
// localStorage.setItem("imageData", image_stu);
// document.getElementById("img_stu").src='data:image/png;base64,' + image_stu;
//alert("DONE");
var events = data.student_details
var l = events.length;
//alert(l);
db.transaction(function(tx) {
tx.executeSql('SELECT * FROM dashboard ', [], function(tx, results){
if (results.rows.length == 0)
{
tx.executeSql("INSERT INTO dashboard(dashboard_id, stu_name,clas,sec,student_image) VALUES(?,?,?,?,?)", [ student_id,data.student_details[0].student_name, data.student_details[0].class_name, data.student_details[0].section_name,data.student_details[0].student_photo], function(tx, res) {
$scope.dashboardDetails();
//alert('INSERTED');
}, function(e) {
//alert('ERROR: ' + e.message);
});
}
});
});
});
$scope.showScreen = function(screen) {
$state.go('app.'+screen);
}
$scope.printDashboard = function()
{
//alert('ss');
db.transaction(function (tx) {
// tx.executeSql('SELECT * FROM dashboard', [], function (tx, dtresult) {
//alert("dtresult.rows.length" + dtresult.rows.length);
// console.log("dtresult.rows.length" + dtresult.rows.length);
// $scope.totalrecords = dtresult.rows.length;
// });
tx.executeSql('SELECT * FROM dashboard', [], function (tx, dresult) {
console.log("dresult.rows.length" + dresult.rows.length);
dataset = dresult.rows;
console.log(dresult.rows);
for (var i = 0, item = null; i < dresult.rows.length; i++) {
item = dataset.item(i);
$scope.dashboarditems.push({stu_name: item['stu_name'],stu_class: item['clas'],stu_sec: item['Sec'],stu_img: item['student_image']});
//$scope.items.push({id: item['notice_title'], notice:item['notice'], event_date: item['event_date']});
console.log($scope.dashboarditems[0]);
}
$state.go('app.dashboard');
});
});
}
$scope.dashboardDetails = function()
{
var citems = [];
syncWithServer(function(syncSuccess){
$scope.printDashboard();
}, false);
}
Question:
How to display my base64 string to image formate.
If your base64 string is present inside the $scope.student_photo
try the following img tag to display the image in view
<img ng-src="{{'data:image/png;base64,'+student_photo}}">

Is it possible to emit data from node/socket to 2 clients at the same time?

I am using emit to send a large amount of data ~1mb when a client connects. For some reason I expected it to not matter how many clients did this at once but now I see that I was likely wrong. It seems that the second client must wait until the first client receives all of the data to start receiving theirs. Is this right and is there any way around it?
var moment = require('moment');
var connect = require('connect'),
socketio = require('socket.io'),
mysql = require('mysql'),
connectionsArray = [],
connection = mysql.createPool({
connectionLimit : 50,
host : '127.0.0.1',
user : 'root',
password : '',
database : 'hideout',
port : 3306
}),
POLLING_INTERVAL = 500,
pollingTimer;
var port = process.env.PORT || 3000;
var server = connect(
connect.static(__dirname + '/public')
).listen(port);
var io = socketio.listen(server);
function initializeDatabase(){
orders=[];
var query2 = connection.query('SELECT open_orders.*,categories.`parent` as parent FROM `open_orders` LEFT JOIN categories ON categories.`id`=open_orders.`category` WHERE `item_parent` IS NULL AND `void` IS NULL ORDER BY `table`,`timestamp`');
query2
.on('error', function(err) {
console.log( err );
updateSocket( err );
})
.on('result', function( order ) {
var theDatetime = moment(order.datetime).format();
var order_item = {
"id":order.id,
"cover":order.cover,
"table_number":order.table,
"seat":order.seat,
"name":order.name,
"price":order.price,
"item_parent":order.item_parent,
"category":order.category,
"non_taxable":order.non_taxable,
"parent":order.parent,
"datetime":theDatetime,
"op_pin":order.op_pin,
"timestamp":order.timestamp,
"menu_id":order.menu_id,
"mod_group_id":order.mod_group_id,
"mod_required":order.mod_required,
"check":order.check,
"split_parent":order.split_parent,
"sent":order.sent,
"complete":order.complete,
"mods":[]
};
orders.push(order_item);
})
.on('end',function(){
});
}
initializeDatabase();
function ordersView(socket){
updateSocket(socket, {orders:orders});
}
io.sockets.on( 'connection', function ( socket ) {
console.log('Number of connections:' + connectionsArray.length);
socket.on('tablesView', function(){
ordersView(socket);
});
socket.on('disconnect', function () {
var socketIndex = connectionsArray.indexOf( socket );
console.log('socket = ' + socketIndex + ' disconnected');
if (socketIndex >= 0) {
connectionsArray.splice( socketIndex, 1 );
}
});
console.log( 'A new socket is connected!' );
connectionsArray.push( socket );
});
var updateSocket = function ( socket, data ) {
data.time = moment(new Date()).format();
socket.emit( 'notification' , data );
};
var updateSockets = function ( socket, data ) {
data.time = moment(new Date()).format();
connectionsArray.forEach(function( tmpSocket ){
if(tmpSocket!==socket){
tmpSocket.volatile.emit( 'notification' , data );
}
});
};

AngularJS ng-repeat view not updating after data update

have a some data one my page that is in a ng-repeat.
When the page and data 1st loads the data shows up.
When I move away from the page (using Angular Routing) make a change to the data (gets saved in db) then come back into the page (make call to db get new data) the ng-repeat data does not refresh. I can see the new data loading into the array and it is the new data.
I start the process on the page with
var sp = this;
sp.viewData = [];
sp.employee = [];
sp.ViewDataTwo = [];
$(document).ready(function () {
var testHeader = setInterval(function () { myTimer() }, 1000);
function myTimer() {
if (addHeaderToken() != undefined) {
clearInterval(testHeader);
sp.usageText = "";
if (sessionStorage.getItem(tokenKey) != null) {
sp.associatedInfo = JSON.parse(getassociatedInfo());
loadDataOne();
loadDataTwo();
}
}
}
});
I do this because I need to get my security toke from a JS script that I have no power over changes. So I need to make sure the code has ran to get me the token.
here are the functions I call..
function loadPasses() {
$http.defaults.headers.common.Authorization = "Bearer " + addHeaderToken();
$http.get('/api/Employee/xxx', { params: { employeeId: sp.employeeId } }).then(function (data) {
sp.viewData = data.data;
for (var i = 0; i < $scope. viewData.length; i++) {
sp.passes[i].sortDateDisplay = (data.data.status == "Active" ? data.data.DateStart + "-" + data.data[i].DateEnd : data.data[i].visitDate);
sp.passes[i].sortDate = (data.data[i].status == "Active" ? data.data[i].DateStart: data.data[i].visitDate);
}
});
}
function loadDataTwo () {
$http.defaults.headers.common.Authorization = "Bearer " + addHeaderToken();
if (sessionStorage.getItem(tokenKey) != null) $http.get('/api/Employee',
{
params: { employeeId: sp.employeeId }
}).then(function (data) {
sp.employee = data.data;
var tempPassString = "";
sp.ViewDataTwo = [];
var totalA = 0;
var totalU = 0;
for (var p = 0; p < sp.employee.dataX.length; p++) {
sp.ViewDataTwo.push(sp.employee.dataX[p].description + "(" + /** math to update description **// + ")");
totalA += parseInt(parseInt(sp.employee.dataX[p].Anumber));
totalU += parseInt(sp.employee.dataX[p].Bnumber));
}
sp.usageArr.push(" Total: " + totalA- totalU) + "/" + totalA + " Available");
//$scope.$apply();
});
}
One my view sp.viewData and sp.ViewDataTwo are both in ng-repeats.
Works well on load.. when I go out and come back in. I see the data reloading. But the view does not.
I have hacked the Dom to get it to work for now. But I would like to do it the right way..
Any help.
I have used
$scope.$apply();
But it tells me the digest is already in process;
the views are in a template..
Please help

Can't $update or $set ~ "undefined is not a function" ~ AngularFire

What I'm trying to do:
Update the status to "TAKEN" when the chat is closed.
Issue:
Can't get $scope.currentChat.$set() or $scope.currentChat.$update() to work when trying to update the status. (See the $scope.close() function.)
What I've tried:
Various methods including $set, $update; I don't know. A lot of things. Been researching this for several hours, and can't find a solution that works.
NOTES:
$scope.currentChat.$set({status:"TAKEN"}); Doesn't work.
$scope.currentChat.$getRecord('status'); Works. Returns:
Object {$value: "OPEN", $id: "status", $priority: null}
So what exactly is going on here? Why can't I seem to set the status to TAKEN?
The issue is currently in the $scope.close() function, when trying to update the status:
// $SCOPE.CLOSE
// - Closes the current ticket.
$scope.close = function() {
// $scope.ticketObject.status = "TAKEN";
// $scope.currentChat.$set({status:"TAKEN"});
console.log("===========================");
console.log("STATUS:");
console.log($scope.currentChat.$getRecord('status'));
console.log($scope.currentChat['status']);
console.log("===========================");
$scope.ticketObject = {};
$scope.ticket = false;
$scope.toggle();
}
Here's my code:
bloop.controller('HomeCtrl', ['$scope', '$firebase', function($scope, $firebase) {
console.log("HomeController!");
var url = 'https://**********.firebaseio.com/tickets/';
var ref = new Firebase(url);
// $SCOPE.CREATETICKET
// - This function makes a connection to Firebase and creates the ticket.
$scope.createTicket = function() {
$scope.tickets = $firebase(ref).$asArray();
$scope.tickets.$add($scope.ticketObject).then(function(r) {
var id = r.name();
$scope.currentFBID = id;
$scope.syncTickets();
console.log("===========================");
console.log("CREATED TICKET: " + $scope.currentFBID);
console.log("URL: " + url + $scope.currentFBID);
console.log("===========================");
});
}
// $SCOPE.SYNCTICKETS
// - This function makes a connection to Firebase and syncs the ticket with the $scope to easily update the tickets.
$scope.syncTickets = function() {
var ticketRefURL = new Firebase(url + $scope.currentFBID);
$scope.currentChat = $firebase(ticketRefURL).$asArray();
$scope.currentChat.$save($scope.ticketObject);
var archiveRefURL = new Firebase(url + $scope.currentFBID + "/archive");
$scope.currentChat.archive = $firebase(archiveRefURL).$asArray();
console.log("===========================");
console.log("SAVED TICKET: " + $scope.currentFBID);
console.log("URL: " + ticketRefURL);
console.log("ARCHIVE URL: " + archiveRefURL);
console.log("===========================");
}
// $SCOPE.POST
// - This function pushes whatever is typed into the chat into the chat archive.
// - $scope.ticketObject.archive (is an array of objects)
$scope.post = function(name) {
// Push to ticketObject.archive array...
$scope.ticketObject.archive.push({
"name" : name,
"text" : $scope.chatText
});
// Logging the array to make sure it exists...
console.log("===========================");
console.log("CHAT ARCHIVE:");
console.log($scope.ticketObject.archive);
console.log("===========================");
$scope.currentChat.archive.$add({
"name" : name,
"text" : $scope.chatText
});
// This resets the text area so it's empty...
$scope.chatText = "";
} // WORKS
// $SCOPE.CLOSE
// - Closes the current ticket.
$scope.close = function() {
// $scope.ticketObject.status = "TAKEN";
// $scope.currentChat.$set({status:"TAKEN"});
console.log("===========================");
console.log("STATUS:");
console.log($scope.currentChat.$getRecord('status'));
console.log($scope.currentChat['status']);
console.log("===========================");
$scope.ticketObject = {};
$scope.ticket = false;
$scope.toggle();
}
// $SCOPE.TOGGLE
// - This function toggles the chat to be either open or closed.
$scope.toggle = function() {
if($scope.toggleState === false) {
$scope.toggleState = true;
$scope.checkTicket();
} else if($scope.toggleState === true) {
$scope.toggleState = false;
}
}
// $SCOPE.CHECKTICKET
// - This function checks to see if there's an existing ticket.
// - If there's not an existing ticket, it creates one.
$scope.checkTicket = function() {
if($scope.ticket === false) {
// Generate New Ticket Data
$scope.ticketObject = newTicket();
// Create the Ticket
$scope.createTicket();
// Ticket now exists.
$scope.ticket = true;
}
}
function newTicket() {
var ticketID = generateTicketID();
var newTicket = {
id: ticketID,
status: "OPEN",
name: "N/A",
email: "N/A",
date: generateDate(),
opID: "Unassigned",
opName: "Unassigned",
archive: [],
notes: []
}
return newTicket;
}
function generateTicketID() {
var chars = "0123456789ABCDEFGHJKLMNPQRSTUVWXYZ";
var result = '';
for(var i=12; i>0; --i) {
result += chars[Math.round(Math.random() * (chars.length - 1))];
}
return result;
}
function generateDate() {
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1;
var yyyy = today.getFullYear();
if(dd < 10) {
dd = '0' + dd;
}
if(mm < 10) {
dd = '0' + mm;
}
var date = mm + "/" + dd + "/" + yyyy;
return date;
}
}]);
$update and $set are part of the $firebase API. You are attempting to call them on the synchronized array returned by $asArray(), which is a $FirebaseArray instance. That has its own API, which includes neither update nor set.

Resources