Synchronous javascript does not work - javascript

I have a script which generates an array of audio files to be played on the click of a button. I am trying to use synchronous JS in order to change the values of some global variables and have been testing for changes with alerts but I get 'undefined' as a result (or my popups do not show).
My code:
jQuery.ajaxSetup({async:false});
var s;
var group;
var curr_rec;
var curr_start = 1;
var curr_end;
var curr_s_obj;
var recs;
var sync = new Array();
var sync_group = new Array();
var check_rec;
var check_id;
var check_start;
var check_end;
var loaded = 0;
var s_obj;
function compare(a,b){
if(a.fields.start_time<b.fields.start_time)
return -1;
if(a.fields.start_time>b.fields.start_time)
return 1;
return 0;
}
function process_data(recs){
for(var i=0;i<recs.length;i++){
check_rec = recs[i];
check_id = check_rec.fields.file_ID;
check_start = check_rec.fields.start_time;
check_end = check_rec_fields.end_time;
if((curr_start.getTime() <= check_start.getTime() && check_end.getTime()<= curr_end.getTime()) ||
(curr_start.getTime()>=check_start.getTime() && curr_start.getTime()<=check_end.getTime()) ||
(curr_end.getTime()>=check_start.getTime() && curr_end.getTime()<=check_end.getTime())
)
{
//diff = (check_start.getTime() - curr_start.getTime())/1000;
//check_rec["difference"] = diff;
sync.push(check_rec);
}
}
}
function load_data(sync){
var diff;
var last = sync[sync.length-1];
for(var j=0;j<sync.length-1;j++){
s_obj = new buzz.sound(sync[i].fields.rec_file);
sync_group.push(s_obj);
diff = (last.fields.start_time.getTime() - sync[i].fields.start_time.getTime())/1000;
if(diff>=0){
s_obj.setTime(diff);
}
else{
alert("error");
}
}
loaded = 1;
}
function synchronise(id){
$.ajax({
type:"GET",
url:"/webapp/playSound:" + id,
success: function(data){
curr_rec = eval("(" + data + ")");
curr_start = curr_rec.fields.start_time;
curr_end= curr_rec.fields.end_time;
curr_s_obj = new buzz.sound(curr_rec.fields.rec_file);
});
alert("ggo");
$.ajax(
type:"GET",
url:"/webapp/getRecs",
success: function(data){
recs = eval("("+ data +")");
process_data(recs);
});
alert(curr_start);
sync = sync.sort(compare);
load_data(sync);
var s1 = new buzz.sound( "../../static/data/second_audio.ogg");
s = new buzz.sound( "../../static/data/" + id +".ogg"); //curr_rec.fields.rec_file
/*
sync_group.push(s);
s.setTime(20.5);
sync_group.push(s1);
*/
group = new buzz.group(sync_group);
}
function playS(id){
if(loaded==0)
synchronise(id);
group.togglePlay();
}
function stopS(){
group.stop();
}

Related

Error with setTimeout() function in for loop

I have the following script that I need to adjust so that each iteration has a one second pause before or after it executes the loop (it doesn't really matter which as long as the lag is there). I tried to add the setTimeout() function into the Try section of my code but it is still consistently failing. I also have tried to use "let" instead of "var" in the for loop but that failed as well. Any advice on how to add it in would be very appreciated. I'm having trouble finding an example of a similar setTimeout() function within a for loop online.
var ZB_DataExtension = 'C7_Unsubscribe_Response';
var ZB_DataExtension_Response = 'C7_Unsubscribe_Response';
var ZB_DataExtension_Logs = 'C7_CustUnsubscribe_Logs';
//Endpoint
var zeroBounceFullUrl = 'https://api.commerce7.com/v1//customer/CUST_ID';
//Extract results from Data Extension using DE key
var results = DataExtension.Init(ZB_DataExtension).Rows.Retrieve();
var updateDE_ZB = DataExtension.Init(ZB_DataExtension_Response);
var logsDE_ZB = DataExtension.Init(ZB_DataExtension_Logs);
var today = Format(Now(), "YYYY-MM-DD ");
for (var i = 0; i < results.length; i++ ) {
var item = results[i];
var zeroBounceUrlItem = "";
var ZB_Status = "";
var currentDateTime = Now();
try{
setTimeout(() => (
zeroBounceUrlItem = String(zeroBounceFullUrl).split("CUST_ID").join(String(item.C7_CustID));
var req = new Script.Util.HttpRequest(zeroBounceUrlItem);
req.emptyContentHandling = 0;
req.retries = 3;
req.continueOnError = true;
req.contentType = "application/json";
req.method = "PUT";
var payload='{"emailMarketingStatus": "Unsubscribed"}'
req.postData = payload ;
var resp = req.send();
var returnStatus= resp.returnStatus;
updateDE_ZB.Rows.Update({C7_API_Answer:String(returnStatus),ValidationDate:currentDateTime,ValidationUrl:String(zeroBounceUrlItem),EmailAddress:String(item.EmailAddress)}, ["C7_CustID"], [String(item.C7_CustID)]);
if (returnStatus==0) {
updateDE_ZB.Rows.Update({C7_API_Answer:String("Success"),ValidationDate:currentDateTime,ValidationUrl:String(zeroBounceUrlItem),EmailAddress:String(item.EmailAddress)}, ["C7_CustID"], [String(item.C7_CustID)]);
}
else {
//ZB_Status = String("ERRO ZB API Call");
//var responseJson = Platform.Function.ParseJSON(String(resp.content));
updateDE_ZB.Rows.Update({C7_API_Answer:String("Failure"),ValidationDate:currentDateTime,ValidationUrl:String(zeroBounceUrlItem),EmailAddress:String(item.EmailAddress)}, ["C7_CustID"], [String(item.C7_CustID)]);
}
var randomID = Platform.Function.GUID();
logsDE_ZB.Rows.Add({log_guid:String(randomID),C7_CustID:String(item.C7_CustID),Status:String("Success"),ValidationDate:currentDateTime,ValidationUrl:String(zeroBounceUrlItem)});
), 1000*i}
catch (err) {
var randomID = Platform.Function.GUID();
ZB_Status = String("ERRO AMPScript");
logsDE_ZB.Rows.Add({log_guid:String(randomID),C7_CustID:String(item.C7_CustID),Status:String("Failure"),ValidationDate:currentDateTime,ValidationUrl:String(zeroBounceUrlItem)});
}
}
</script>
Your loop will execute the right number of times and at the right interval, but the value of the variable item inside the timeout might not be what you expect.
Try this:
for (var i = 0; i < results.length; i++ ) {
(function(i){
setTimeout(function(){
var item = results[i];
var zeroBounceUrlItem = "";
var ZB_Status = "";
var currentDateTime = Now();
try{
zeroBounceUrlItem = String(zeroBounceFullUrl).split("CUST_ID").join(String(item.C7_CustID));
var req = new Script.Util.HttpRequest(zeroBounceUrlItem);
req.emptyContentHandling = 0;
req.retries = 3;
req.continueOnError = true;
req.contentType = "application/json";
req.method = "PUT";
var payload='{"emailMarketingStatus": "Unsubscribed"}'
req.postData = payload ;
var resp = req.send();
var returnStatus= resp.returnStatus;
updateDE_ZB.Rows.Update({C7_API_Answer:String(returnStatus),ValidationDate:currentDateTime,ValidationUrl:String(zeroBounceUrlItem),EmailAddress:String(item.EmailAddress)}, ["C7_CustID"], [String(item.C7_CustID)]);
if (returnStatus==0) {
updateDE_ZB.Rows.Update({C7_API_Answer:String("Success"),ValidationDate:currentDateTime,ValidationUrl:String(zeroBounceUrlItem),EmailAddress:String(item.EmailAddress)}, ["C7_CustID"], [String(item.C7_CustID)]);
}
else {
//ZB_Status = String("ERRO ZB API Call");
//var responseJson = Platform.Function.ParseJSON(String(resp.content));
updateDE_ZB.Rows.Update({C7_API_Answer:String("Failure"),ValidationDate:currentDateTime,ValidationUrl:String(zeroBounceUrlItem),EmailAddress:String(item.EmailAddress)}, ["C7_CustID"], [String(item.C7_CustID)]);
}
var randomID = Platform.Function.GUID();
logsDE_ZB.Rows.Add({log_guid:String(randomID),C7_CustID:String(item.C7_CustID),Status:String("Success"),ValidationDate:currentDateTime,ValidationUrl:String(zeroBounceUrlItem)});
catch (err) {
var randomID = Platform.Function.GUID();
ZB_Status = String("ERRO AMPScript");
logsDE_ZB.Rows.Add({log_guid:String(randomID),C7_CustID:String(item.C7_CustID),Status:String("Failure"),ValidationDate:currentDateTime,ValidationUrl:String(zeroBounceUrlItem)});
}
}, i*1000);
})(i);
}

Wait Callback and our result data to take another proccess out of this function

i have this class (product).
var Product = function () {
this.products = [];
this.priceFrom = null;
this.priceTo = null;
this.countDone = 0;
};
Product.prototype = {
constructor: Product,
getProductsByPriceRange: function (priceFrom, priceTo) {
var xhrUrl = "<?= base_url('market/products/xhr_product_price_range') ?>";
var xhrData = {price_from: priceFrom, price_to: priceTo};
var xhrType = "json";
var UtilsClass = new Utils();
UtilsClass.xhrConnection(xhrUrl, xhrData, xhrType, function (data) {
/* MY DATA IS HERE */
});
},
buildList:function (products) {
for (var i = 0; i < products.length; i++) {
var product = products[i];
console.log("product");
}
},
buildOne: function (product) {
}
};
/*....more classes */
And another piece of code (out of product class):
var fromPrice = data.from;
var toPrice = data.to;
var ProductClass = new Product();
var lastCountDone = ProductClass.countDone;
ProductClass.priceFrom = fromPrice;
ProductClass.priceTo = toPrice;
var myProducts = ProductClass.getProductsByPriceRange(ProductClass.priceFrom, ProductClass.priceTo);
My question is... can i wait callback of UtilsClass.xhrConnection (in first piece) and use generated data of callback in second piece of code (out of first piece).
Any ideas would be very valuable to me. Thank you!
var Product = function () {
this.products = [];
this.priceFrom = null;
this.priceTo = null;
this.countDone = 0;
};
Product.prototype = {
constructor: Product,
getProductsByPriceRange: function (priceFrom, priceTo) {
var xhrUrl = "<?= base_url('market/products/xhr_product_price_range') ?>";
var xhrData = {price_from: priceFrom, price_to: priceTo};
var xhrType = "json";
var UtilsClass = new Utils();
return new Promise(function(resolve, reject){
UtilsClass.xhrConnection(xhrUrl, xhrData, xhrType, function (data) {
/* MY DATA IS HERE */
resolve(data)
});
});
},
buildList:function (products) {
for (var i = 0; i < products.length; i++) {
var product = products[i];
console.log("product");
}
},
buildOne: function (product) {
}
};
While calling,
var fromPrice = data.from;
var toPrice = data.to;
var ProductClass = new Product();
var lastCountDone = ProductClass.countDone;
ProductClass.priceFrom = fromPrice;
ProductClass.priceTo = toPrice;
var myProducts = ProductClass.getProductsByPriceRange(ProductClass.priceFrom, ProductClass.priceTo).then(function(data){%your data will be available here%});

Count how many times i have the same word

My variable tag returns one of these 4 different values: assistance, bug, evolution or maintenance. I would like to count how many times I have each of those words. I would like to display how many times I have each of those item in my console first. I really don't know how to do that. Here is my code :
function displaytickets(y){
$.ajax({
url: "https://cubber.zendesk.com/api/v2/users/" + y + "/tickets/requested.json?per_page=150",
type: 'GET',
dataType: 'json',
cors: true ,
contentType: 'application/json',
secure: true,
beforeSend: function(xhr) {
xhr.setRequestHeader ("Authorization", "Basic " + btoa(""));
},
success: function(data) {
var sortbydate = data.tickets.sort(function(a, b){
return new Date(b.created_at) - new Date(a.created_at);
});
var ids = $.map(data.tickets, function (data) {
return data.id;
})
localStorage.setItem("mesid", ids);
for (i = 0; i < data.tickets.length; i++) {
var myticket = data.tickets[i];
var mydate = data.tickets[i].created_at;
var created = moment(mydate).format("MM-DD-YY");
var mytitle = data.tickets[i].subject;
var description = data.tickets[i].description;
var status = data.tickets[i].status;
var tag = data.tickets[i].tags[0];
console.log(tag);
var myid = data.tickets[i].id;
}
var nbticket = data.tickets.length;
$("#name").append('<h2 class="title">' + " " + nbticket + " ticket(s)" + '</h2>');
},
});
}
Here's what I get from the console for the console.log(tag):
You can achieve this by using an object to store the occurrence count, keyed by the string itself. Try this:
var occurrences = {};
Then in your success handler you can add and increment the tags as you find them:
success: function(data) {
// your code here...
for (i = 0; i < data.tickets.length; i++) {
// your code here...
var tag = data.tickets[i].tags[0];
if (occurrences.hasOwnProperty(tag)) {
occurrences[tag]++;
} else {
occurrences[tag] = 1;
}
}
console.log(occurrences);
},
Working example
Did you try to count it in your for loop ?
var maintenance_counter = 0;
for (i = 0; i < data.tickets.length; i++) {
var myticket = data.tickets[i];
var mydate = data.tickets[i].created_at;
var created = moment(mydate).format("MM-DD-YY");
var mytitle = data.tickets[i].subject;
var description = data.tickets[i].description;
var status = data.tickets[i].status;
var tag = data.tickets[i].tags[0];
var myid = data.tickets[i].id;
if( tag == "maintenance" ){
maintenance_counter++;
}
}
alert("Total maintenance occurrence:"+ maintenance_counter);
Create an object to hold your tag result count, similar to this:
var tagCount = {};
for (i = 0; i < data.tickets.length; i++) {
var tag = data.tickets[i].tags[0];
if (tagCount[tag] === undefined) {
tagCount[tag] = 1;
} else {
tagCount[tag] += 1;
}
}
console.log(tagCount);

Set globa Variables From JSON Variables

So I have an update function in javascript that get's json variables from a file. I'm using the variables in other functions, and I'm having to call the same file for that function. I'm wanting to set those variables to be global so I won't have to call the file in the other function, Here's the update function:
function XML() {
$.ajax({
type: "GET",
url: "xmlconnect.php",
dataType: "json",
success: function(data) {
for (var i in data) {
var data = data[i];
var level = data[4];
var cash = data[6];
var income = data[7];
var upkeep = data[42];
var total_income = income - upkeep;
var eincome = data[46];
var health = data[10];
var max_health = data[11];
var energy = data[12];
var max_energy = data[13];
var stamina = data[14];
var max_stamina = data[15];
var Exp = data[8];
var max_exp = data[9];
var attack = data[16];
var defense = data[17];
var skill_points = data[24];
var health_width = health / max_health * 100;
var energy_width = energy / max_energy * 100;
var stamina_width = stamina / max_stamina * 100;
var exp_width = Exp / max_exp * 100;
var sess_id = data['sess'];
if(cash < 1000) {
var user_cash = number_format(cash);
}
else {
var user_cash = format(cash);
}
$('#Cash').html('$'+format(user_cash));
$('#Income').html('$'+number_format(total_income));
$('#EIncome').html(number_format(eincome));
$('#LevelText').html(level);
$('#HealthText').html(format(health)+'/'+format(max_health));
$('#EnergyText').html(format(energy)+'/'+format(max_energy));
$('#StaminaText').html(format(stamina)+'/'+format(max_stamina));
$('#ExpText').html(number_format(exp_width)+'%');
$('#HealthWidth').css('width',''+health_width+'%');
$('#EnergyWidth').css('width',''+energy_width+'%');
$('#StaminaWidth').css('width',''+stamina_width+'%');
$('#ExpWidth').css('width',''+exp_width+'%');
$('#Update').load('activity.php');
}
}
});
}
And for instance I need to use a few of those variables in another function called "Increase" And I have it setup like this:
function Increase(Att) {
$.ajax({
type: "GET",
url: "xmlconnect.php",
dataType: "json",
success: function(data) {
for (var i in data) {
var data = data[i];
var max_health = data[11];
var max_energy = data[13];
var max_stamina = data[15];
var attack = data[16];
var defense = data[17];
var skill_points = data[24];
$('#AttResults').load('increase.php?att='+Att);
$('#Skills').html(number_format(skill_points));
$('#Att_attack').html(number_format(attack));
$('#Att_defense').html(number_format(defense));
$('#Att_max_health').html(number_format(max_health));
$('#Att_max_energy').html(number_format(max_energy));
$('#Att_max_stamina').html(number_format(max_stamina));
XML();
}
}
});
}
But I want to make the first XML Function to be global Variables.
As per W3Schools you can simply do:
variable = value;
(yes, without 'var') and it will make it a global variable unless that same name is used in another scope.

Asynchronous execution of javascript code

I am studying javascript and json but I've some problems: I have a script that works with json but the performances of what I wrote aren't that good. The code works only if I do a debug step by step with firebug or other tools and that makes me think that the execution of the code (or a part of it ... the one that creates the table as you'll see) requires too much time so the browser stops it.
The code is:
var arrayCarte = [];
var arrayEntita = [];
var arraycardbyuser = [];
function displayArrayCards() {
var richiestaEntity = new XMLHttpRequest();
richiestaEntity.onreadystatechange = function() {
if(richiestaEntity.readyState == 4) {
var objectentityjson = {};
objectentityjson = JSON.parse(richiestaEntity.responseText);
arrayEntita = objectentityjson.cards;
}
}
richiestaEntity.open("GET", "danielericerca.json", true);
richiestaEntity.send(null);
for(i = 0; i < arrayEntita.length; i++) {
var vanityurla = arrayEntita[i].vanity_urls[0] + ".json";
var urlrichiesta = "http://m.airpim.com/public/vurl/";
var richiestaCards = new XMLHttpRequest();
richiestaCards.onreadystatechange = function() {
if(richiestaCards.readyState == 4) {
var objectcardjson = {};
objectcardjson = JSON.parse(richiestaCards.responseText);
for(j = 0; j < objectcardjson.cards.length; j++)
arrayCarte[j] = objectcardjson.cards[j].__guid__; //vettore che contiene i guid delle card
arraycardbyuser[i] = arrayCarte;
arrayCarte = [];
}
}
richiestaCards.open("GET", vanityurla, true);
richiestaCards.send(null);
}
var wrapper = document.getElementById('contenitoro');
wrapper.innerHTML = "";
var userTable = document.createElement('table');
for(u = 0; u < arrayEntita.length; u++) {
var userTr = document.createElement('tr');
var userTdcard = document.createElement('td');
var userTdinfo = document.createElement('td');
var br = document.createElement('br');
for(c = 0; c < arraycardbyuser[u].length; c++) {
var cardImg = document.createElement('img');
cardImg.src = "http://www.airpim.com/png/public/card/" + arraycardbyuser[u][c] + "?width=292";
cardImg.id = "immaginecard";
userTdcard.appendChild(br);
userTdcard.appendChild(cardImg);
}
var userdivNome = document.createElement('div');
userdivNome.id = "diverso";
userTdinfo.appendChild(userdivNome);
var userdivVanity = document.createElement('div');
userdivVanity.id = "diverso";
userTdinfo.appendChild(userdivVanity);
var nome = "Nome: ";
var vanityurl = "Vanity Url: ";
userdivNome.innerHTML = nome + arrayEntita[u].__title__;
userdivVanity.innerHTML = vanityurl + arrayEntita[u].vanity_urls[0];
userTr.appendChild(userTdcard);
userTr.appendChild(userTdinfo);
userTable.appendChild(userTr);
}
wrapper.appendChild(userTable);
}
The problem is that the code that should make the table doesn't wait for the complete execution of the code that works with the json files. How can I fix it? I would prefer,if possible, to solve that problem with something easy, without jquery and callbacks (I am a beginner).
You'll have to move som code around to make that work. at first, split it up in some functions, then it is easier to work with. I dont know if it works, but the idea is that first it loads the arrayEntita. When that is done, it fills the other 2 arrays. And when the last array has been filled, it builds the table.
var arrayCarte = [];
var arrayEntita = [];
var arraycardbyuser = [];
function displayArrayCards() {
var richiestaEntity = new XMLHttpRequest();
richiestaEntity.onreadystatechange = function () {
if (richiestaEntity.readyState == 4) {
var objectentityjson = {};
objectentityjson = JSON.parse(richiestaEntity.responseText);
arrayEntita = objectentityjson.cards;
BuildArrayEntita();
}
}
richiestaEntity.open("GET", "danielericerca.json", true);
richiestaEntity.send(null);
}
function BuildArrayEntita() {
for (i = 0; i < arrayEntita.length; i++) {
var vanityurla = arrayEntita[i].vanity_urls[0] + ".json";
var urlrichiesta = "http://m.airpim.com/public/vurl/";
var richiestaCards = new XMLHttpRequest();
richiestaCards.onreadystatechange = function () {
if (richiestaCards.readyState == 4) {
var objectcardjson = {};
objectcardjson = JSON.parse(richiestaCards.responseText);
for (j = 0; j < objectcardjson.cards.length; j++)
arrayCarte[j] = objectcardjson.cards[j].__guid__; //vettore che contiene i guid delle card
arraycardbyuser[i] = arrayCarte;
arrayCarte = [];
//If it is the last call to populate arraycardbyuser, build the table:
if (i + 1 == arrayEntita.length)
BuildTable();
}
}
richiestaCards.open("GET", vanityurla, true);
richiestaCards.send(null);
}
}
function BuildTable() {
var wrapper = document.getElementById('contenitoro');
wrapper.innerHTML = "";
var userTable = document.createElement('table');
for (u = 0; u < arrayEntita.length; u++) {
var userTr = document.createElement('tr');
var userTdcard = document.createElement('td');
var userTdinfo = document.createElement('td');
var br = document.createElement('br');
for (c = 0; c < arraycardbyuser[u].length; c++) {
var cardImg = document.createElement('img');
cardImg.src = "http://www.airpim.com/png/public/card/" + arraycardbyuser[u][c] + "?width=292";
cardImg.id = "immaginecard";
userTdcard.appendChild(br);
userTdcard.appendChild(cardImg);
}
var userdivNome = document.createElement('div');
userdivNome.id = "diverso";
userTdinfo.appendChild(userdivNome);
var userdivVanity = document.createElement('div');
userdivVanity.id = "diverso";
userTdinfo.appendChild(userdivVanity);
var nome = "Nome: ";
var vanityurl = "Vanity Url: ";
userdivNome.innerHTML = nome + arrayEntita[u].__title__;
userdivVanity.innerHTML = vanityurl + arrayEntita[u].vanity_urls[0];
userTr.appendChild(userTdcard);
userTr.appendChild(userTdinfo);
userTable.appendChild(userTr);
}
wrapper.appendChild(userTable);
}
i dont know if this check:
if (i + 1 == arrayEntita.length)
BuildTable();
but else you have to check if alle responseses have returned before executing buildtable();
AJAX requests are asynchronous. They arrive at an unknown period during execution and JavaScript does not wait for the server to reply before proceeding. There is synchronous XHR but it's not for ideal use. You'd lose the whole idea of AJAX if you do so.
What is usually done is to pass in a "callback" - a function that is executed sometime later, depending on when you want it executed. In your case, you want the table to be generated after you receive the data:
function getData(callback){
//AJAX setup
var richiestaEntity = new XMLHttpRequest();
//listen for readystatechange
richiestaEntity.onreadystatechange = function() {
//listen for state 4 and ok status (200)
if (richiestaEntity.readyState === 4 && richiestaEntity.status === 200) {
//execute callback when data is received passing it
//what "this" is in the callback function, as well as
//the returned data
callback.call(this,richiestaEntity.responseText);
}
}
richiestaEntity.open("GET", "danielericerca.json"); //third parameter defaults to true
richiestaEntity.send();
}
function displayArrayCards() {
//this function passed to getData will be executed
//when data arrives
getData(function(returnedData){
//put here what you want to execute when getData receives the data
//"returnedData" variable inside this function is the JSON returned
});
}
As soon as you have made the ajax call, put all of the rest of the code inside the readystatechange function. This way, it will execute everything in order.
Edit: #Dappergoat has explained it better than I can.

Categories

Resources