the code below must display a table as represented the top the buttons must be present and once I click on the button an underlying text is displayed, the problem is that if you click on the last button the buttons at the top remain fixed, if I click on another button the buttons at the top are shown at the bottom, I assume it is a jquery problem I see to report the screens below to better explain the problem.
React Code:
private AppendButtonsPeoplePicker() {
// Email
let inputEmail: JQuery<HTMLInputElement> =
this.Fields.TxT_RichiedenteEmail.find("input");
const labelEmail =
this.Fields.TxT_RichiedenteEmail.closest("tr").find("nobr")[0].innerText;
this.BuildButtonForPeoplePicker(
inputEmail,
TicketConstants.RichiedenteEmail,
labelEmail
);
// CC
let inputCC: JQuery<HTMLInputElement> = this.Fields.TxT_CC.find("input");
const labelCC = this.Fields.TxT_CC.closest("tr").find("nobr")[0].innerText;
this.BuildButtonForPeoplePicker(inputCC, TicketConstants.CC, labelCC);
// CCN
let inputCCN: JQuery<HTMLInputElement> = this.Fields.TxT_CCN.find("input");
const labelCCN =
this.Fields.TxT_CCN.closest("tr").find("nobr")[0].innerText;
this.BuildButtonForPeoplePicker(inputCCN, TicketConstants.CCN, labelCCN);
//Recupero la lista delle risposte
try {
// Recupero l'id del ticket
let idTicket: string = localStorage.getItem("IdTicket");
// Ricava da SharePoint le risposte relative al ticket.
// Non prende in considerazione la risposta con il flag Bozza attivo.
let context: SP.ClientContext = SP.ClientContext.get_current();
let web: SP.Web = context.get_web();
let list: SP.List = web
.get_lists()
.getByTitle(RisposteConstants.ListTitle);
let query: SP.CamlQuery = new SP.CamlQuery();
query.set_viewXml(`
<View>
<Query>
<Where>
<And>
<Eq>
<FieldRef Name="${RisposteConstants.Ticket}" LookupId="TRUE" />
<Value Type="Lookup">${idTicket}</Value>
</Eq>
<Or>
<IsNull>
<FieldRef Name="${RisposteConstants.Bozza}" />
</IsNull>
<Eq>
<FieldRef Name="${RisposteConstants.Bozza}" />
<Value Type="Boolean">0</Value>
</Eq>
</Or>
</And>
</Where>
<OrderBy>
<FieldRef Name="ID" Ascending='True'></FieldRef>
</OrderBy>
</Query>
</View>`);
let itemsColl: SP.ListItemCollection<RisposteListItem> =
list.getItems(query);
context.load(itemsColl);
context.load(web);
$(".ms-formtable").append("<br> </br><div class='tabcontents'> <table>");
// Recupero la url del sito per configurare il download dei file allegati
var site = context.get_site();
context.load(site, "Url");
context.executeQueryAsync(
async function () {
var oListItemEnumerators = itemsColl.getEnumerator();
var i = 1;
while (oListItemEnumerators.moveNext()) {
let item = oListItemEnumerators.get_current();
var value = item.get_item("Risposta");
var ValueID = item.get_item("ID");
// Recupero l'autore del file
var Authorstring = item.get_item("Author");
var created = item.get_item("Created");
var Author =
Authorstring.get_lookupValue() + " " + created.toLocaleString();
let button = $(
"<td> <button class='call-btn'>Risposta " + i + "</button> "
);
$(".tabcontents").append(button);
var id = "container-ticket" + i;
// Aggiungo la risposta in append nascondendola di default
let risposta = $(
"<div id=" +
id +
" class='container-ticket' name='review' rows='4' cols='100'>" +
Author +
"\n\n" +
value +
"</div> </td>"
);
// Nascondo la risposta
risposta.hide();
// Append container allegati
var attachmentFiles = item.get_attachmentFiles();
context.load(attachmentFiles);
// Esecuzione della query
await new Promise((resolve, reject) => {
context.executeQueryAsync(
() => {
if (attachmentFiles.get_count() > 0) {
var attachmentsItemsEnumerator =
attachmentFiles.getEnumerator();
while (attachmentsItemsEnumerator.moveNext()) {
var attachitem = attachmentsItemsEnumerator.get_current();
var fileName = attachitem.get_fileName();
//Costruisco la url per il download dei file url server di test https://webapptest.regione.emilia-romagna.it/app/erri
var urlfile =
site.get_url() +
"/gestione/Lists/Risposte/Attachments/" +
ValueID +
"/" +
fileName;
//Ora inserisco la url del file in append per scaricare il file
risposta.append(
"<br> <a href=" +
urlfile +
">" +
fileName +
"</a> </br>"
);
}
} else {
console.log("Nessun allegato");
}
resolve(null);
},
(sender: any, args: SP.ClientRequestFailedEventArgs) => {
console.log(
`Fallita la query su SharePoint per la ricerca degli allegati della risposta (id ticket: ${idTicket} - id risposta: ${ValueID})`,
sender,
args.get_message(),
args.get_stackTrace()
);
reject();
}
);
});
$(".tabcontents").append(risposta);
button.click(function (evt) {
evt.stopPropagation();
evt.preventDefault();
$(".container-desc").hide();
$(".container-ticket").hide();
$(".tab button.selected").removeClass("selected");
button.addClass("selected");
risposta.show();
return false;
});
i++;
}
},
function (sender: any, args: SP.ClientRequestFailedEventArgs) {
console.log(
`Fallita la query su SharePoint per la ricerca delle risposte del ticket (id ticket: ${idTicket})`,
sender,
args.get_message(),
args.get_stackTrace()
);
}
);
$(".tabcontents").append("</table></div>");
} catch (err) {
console.log("Errore: " + err);
}
}
Related
I have this program that as soon as it starts up, it asks you to enter the number of books that you want to register in the program and the number of authors that each book will have.
The program will ask you to register a name for each author, surname, age and nationality.
Once this is done, there is a button that shows all the books registered with their authors and the data of the books, and I have the problem that I am not able to show the data of the authors since only [object Object] appears.
Edit:
I have managed to print the element.autores by console.log, without the error obejct object appearing but I am not able to get it out through a document.write or something similar, here I leave a screenshot of how it should appear:
And if I try to put elements.autores.nombre to print only the name, it appears undefined both in the console.log and in the document.write
Here my code:
javascript:
var biblioteca = new Array();
function libro(titulo, autores, anyo, editorial) {
this.titulo = titulo;
this.autores = autores;
this.anyo = anyo;
this.editorial = editorial;
}
function autor(nombre, apellidos, edad, nacionalidad) {
this.nombre = nombre;
this.aepellidos = apellidos;
this.edad = edad;
this.nacionalidad = nacionalidad;
}
window.onload = function () {
document.getElementById("mostrar").onclick = Mostrar;
document.getElementById("insertar").onclick = insertarlibro;
document.getElementById("insertar").onclick = insertarautor;
}
function insertarlibro() {
var autores = new Array();
var titulo = prompt("Insertar el nombre del titulo del libro");
var anyo = parseInt(prompt("Año"));
var editorial = prompt("Inserta su editorial");
var numautores = parseInt(prompt("Cuantos autores vas a insertar"));
for (let i = 0; i < numautores; i++) {
let autor = insertarautor();
autores.push(autor);
}
var registrohecho = new libro(titulo, autores, anyo, editorial);
return registrohecho;
}
console.log(insertarlibro);
function insertarautor() {
var nombre = prompt("Insertar el nombre del autor").toUpperCase();
var apellidos = prompt("Insertar el apellidos del autor").toUpperCase();
var edad = parseInt(prompt("Edad"));
var nacionalidad = prompt("¿De que pais es el autor?");
var registrohecho = new autor(nombre, apellidos, edad, nacionalidad);
return registrohecho;
}
console.log(insertarautor);
var numlibros = parseInt(prompt("Cuantos libros vas a insertar"));
for (let i = 0; i < numlibros; i++) {
var insertalibro = insertarlibro();
biblioteca.push(insertalibro);
}
function Mostrar() {
biblioteca.forEach(element => {
console.log("Error" + JSON.stringify(element.autores));
var muestra = "Nombre del libro:" + element.titulo + " autores: " + element.autores + " Año en el que se publico: " + element.anyo + " Editorial: " + element.editorial;
document.write(muestra);
});
}
And the html part:
<div id="insertar">
<input type="button" value="Insertar">
</div>
<div id="mostrar">
<input type="button" value="Mostrar">
</div>
You are trying to get element.autores, which is an array. To get e.g. get the nombre, you wold have to acces it with element.autores[0].nombre.
So your code to output all books (with authors) would be something like this:
biblioteca.forEach(element => {
var muestra = "Nombre del libro:" + element.titulo + " autores: ";
element.autores.forEach(author => {
muestra += `nombre: ${author.nombre}, aepellidos: ${author.aepellidos}, edad: ${author.edad}, nacionalidad: ${author.nacionalidad} `;
})
muestra += "Año en el que se publico: " + element.anyo + " Editorial: " + element.editorial;
document.write(muestra);
});
I have the following script that takes the inputs on Google Forms, makes a document with those inputs, and sends an e-mail with the document attached. It works properly, but I needed to filter some of the responses, but I don't know how to filter data in an event.
One of the questions on the forms is asking what kind of document people want:
Right now, I have only done the script for the 2nd option (Licença Especial em Pecúnia). I need to filter the data from the forms, so when I choose the 1st option (Substituição de Chefia) it generates a different document from a different template. Right now, the function afterSubmit(e) is triggered on form submit.
Excuse the portuguese names of vars and consts, the important ones for this questions I changed to english.
function afterSubmit(e) {
const info = e.namedValues;
const pdfFileLP = createPDFLP(info);
const url = e.namedValues['Anexos ao ofício'][0];
function getIdFromUrl(url) {return url.match(/[-\w]{25,}$/);};
var idAnexo = getIdFromUrl(url);
const nrof = e.namedValues['Numeração do ofício'][0];
function pdfAnexado(idAnexo,nrof) {return DriveApp.getFileById(idAnexo).setName("Anexos do ofício of. " + nrof + "-PGE/PRF.pdf");};
var pdfAnexo = pdfAnexado(idAnexo);
eprotocolo(e.namedValues['Expresso do solicitante'][0],nrof,pdfFileLP,pdfAnexo);
}
function eprotocolo(email,ofi,pdfFileLP,pdfAnexo){
var EmailTemp = HtmlService.createTemplateFromFile("mailLP");
EmailTemp.mail = email;
var htmlMessage = EmailTemp.evaluate().getContent();
GmailApp.sendEmail("estag.pedron#pge.pr.gov.br","Of. " + ofi + "-PGE/PRF",
"SEU EMAIL NÃO SUPORTA O FORMATO HTML, FAVOR RESPONDER ESTE E-MAIL PARA SOLUCIONAR O PROBLEMA OU ENTRAR EM CONTATO PELO TELEFONE (41)3281-6392.",{
from: "procuradoriafuncional#gmail.com", name: "Gerador de ofícios da PRF", htmlBody: htmlMessage,
replyTo: email, cc: email,
attachments: [pdfFileLP, pdfAnexo]
});
}
function createPDFLP(info) {
const pdfFolder = DriveApp.getFolderById("1mgNPhM9f2U0BWrDK0FAfCYyq968rJ3E8");
const tempFolder = DriveApp.getFolderById("1FfW3Jn9hHARpBU8t8szlQ2YwR9OPR1ZV");
const templateChefia = DriveApp.getFileById("1qP3A8O27Ms8OuybaqrQ6jQBB_PQpo-RhDU9xjIw_a44");
const templateLP = DriveApp.getFileById("1lRab5lPdbRcdl4gaI3zonFseE180cNu4-hWaovamerc");
const newTempFileLP = templateLP.makeCopy(tempFolder);
const openDocLP = DocumentApp.openById(newTempFileLP.getId());
const bodyLP = openDocLP.getBody();
bodyLP.replaceText("{of}", info['Numeração do ofício'][0]);
bodyLP.replaceText("{data}", info['Data do ofício'][0]);
bodyLP.replaceText("{serv}", info['Nome completo'][0]);
bodyLP.replaceText("{rg}", info['Número do RG'][0]);
bodyLP.replaceText("{autos}", info['Numero dos autos'][0]);
bodyLP.replaceText("{prazo}", info['Prazo'][0]);
bodyLP.replaceText("{procurador}", info['Procurador solicitante'][0]);
bodyLP.replaceText("{orgao}", info['GRHS de destino'][0]);
openDocLP.saveAndClose();
const blobPDFLP = newTempFileLP.getAs(MimeType.PDF);
const pdfFileLP = pdfFolder.createFile(blobPDFLP).setName("Of. " + info['Numeração do ofício'][0] + "-PGE/PRF.pdf");
tempFolder.removeFile(newTempFileLP);
return pdfFileLP;}
If anyone was curious, I did a simple if statement at the end:
function createPDFLP(info) {
const pdfFolder = DriveApp.getFolderById("1mgNPhM9f2U0BWrDK0FAfCYyq968rJ3E8");
const tempFolder = DriveApp.getFolderById("1FfW3Jn9hHARpBU8t8szlQ2YwR9OPR1ZV");
const templateChefia = DriveApp.getFileById("1qP3A8O27Ms8OuybaqrQ6jQBB_PQpo-RhDU9xjIw_a44");
const templateLP = DriveApp.getFileById("1lRab5lPdbRcdl4gaI3zonFseE180cNu4-hWaovamerc");
const tipo = info['Tipo de ofício'][0];
if(tipo == "Licença Especial em Pecúnia"){
const newTempFileLP = templateLP.makeCopy(tempFolder);
const openDocLP = DocumentApp.openById(newTempFileLP.getId());
const bodyLP = openDocLP.getBody();
bodyLP.replaceText("{of}", info['Numeração do ofício'][0]);
bodyLP.replaceText("{data}", info['Data do ofício'][0]);
bodyLP.replaceText("{serv}", info['Nome completo'][0]);
bodyLP.replaceText("{rg}", info['Número do RG'][0]);
bodyLP.replaceText("{autos}", info['Numero dos autos'][0]);
bodyLP.replaceText("{prazo}", info['Prazo'][0]);
bodyLP.replaceText("{procurador}", info['Procurador solicitante'][0]);
bodyLP.replaceText("{orgao}", info['GRHS de destino'][0]);
openDocLP.saveAndClose();
const blobPDFLP = newTempFileLP.getAs(MimeType.PDF);
const pdfFileLP = pdfFolder.createFile(blobPDFLP).setName("Of. " + info['Numeração do ofício'][0] + "-PGE/PRF.pdf");
tempFolder.removeFile(newTempFileLP);
return pdfFileLP;
} else if (tipo == "Substituição de Chefia") {
const newTempFileSC = templateChefia.makeCopy(tempFolder);
const openDocSC = DocumentApp.openById(newTempFileSC.getId());
const bodySC = openDocSC.getBody();
bodySC.replaceText("{of}", info['Numeração do ofício'][0]);
bodySC.replaceText("{data}", info['Data do ofício'][0]);
bodySC.replaceText("{servi}", info['Nome completo'][0]);
bodySC.replaceText("{rg}", info['Número do RG'][0]);
bodySC.replaceText("{autos}", info['Numero dos autos'][0]);
bodySC.replaceText("{prazo}", info['Prazo'][0]);
bodySC.replaceText("{procurador}", info['Procurador solicitante'][0]);
bodySC.replaceText("{orgao}", info['GRHS de destino'][0]);
bodySC.replaceText("{periodo}", info['Período que o autor alega que ocupou cargo de chefia'][0]);
openDocSC.saveAndClose();
const blobPDFSC = newTempFileSC.getAs(MimeType.PDF);
const pdfFileLP = pdfFolder.createFile(blobPDFSC).setName("Of. " + info['Numeração do ofício'][0] + "-PGE/PRF.pdf");
tempFolder.removeFile(newTempFileSC);
return pdfFileLP;
}
}
So already hello to all & especially to those who will take the trouble to help me, I have a project to verify the user thanks to a hash decryption challenge system (base64) & that when they are successful its giving them a role to check, I did a good part of it but its not right I don't understand my mistake! the bot connects, 0 code errors, but the verification does not work I would like the verification to be done in the channel & not in the DM! thank you
const Discord = require('discord.js')
const client = new Discord.Client();
const prefix = "&";
let rawdata = fs.readFileSync('config.json');
let object = JSON.parse(rawdata);
var channel_id = object['verification_channelID']
var guild_id = object['guild_ID']
var role_name = object['verification_role_name']
var server_invite = object['server_invite']
var token = object['bot_token']
var questions = object['questions']
var dict = {};
var encodingQuestions = []
questions.forEach(element => {
encodingQuestions.push(element)
});
client.on('ready', function(){
console.log("Login : " + client.user.tag);
})
client.on('guildMemberAdd', member => {
var uname = member.user.username
var disc = member.user.discriminator
var memberID = member.user.id
var rand = Math.random();
rand *= encodingQuestions.length;
rand = Math.floor(rand);
var question = encodingQuestions[rand]
dict[uname] = [Buffer.from(question, 'base64').toString('utf-8'), 3];
const embed = new Discord.MessageEmbed()
.setTitle(uname + "#" + disc)
.setColor(0x1e90ff)
.addField(uname='Welcome', value='Welcome <#' + memberID + '> Déchiffrer le code , vous avez 3 essais ! Utilisez ``&answer {decoded message}`` ', inline=false)
.addField(uname='Question', value=question, inline=false)
member.send(embed)
member.guild.channels.cache.get(channel_id).send("Welcome <#" + memberID + "> Regarder vos DM pour accédez au serveur !")
});
client.on('message', message => {
var memberid = message.author.id;
var memberuname = message.author.username;
var messagecontent = message.content;
var messageID = message.id;
var disc = message.author.discriminator;
if (!message.content.startsWith(prefix)) return;
if (message.content.startsWith(prefix + 'answer') && message.channel.type === "dm"){
var msg = message.toString().replace('&answer ', '')
for (var key in dict){
if (key == message.author.username){
if (msg == dict[key][0]){
message.channel.send("Vous avez passer le test !")
var role = client.guilds.cache.get(guild_id).roles.cache.find(role => role.name === role_name)
client.guilds.cache.get(guild_id).members.cache.get(message.author.id).roles.add(role);
var memberID = message.author.id
client.channels.cache.get(channel_id).send("Trés bien <#" + memberID + "> vous avez réussis le test avec succèes !")
delete dict[key];
} else{
dict[key][1] = dict[key][1] - 1
if (dict[key][1] == 0){
memberID = message.author.id
message.channel.send("Vous avez pas réussis le test vous allez êtres exclus ! Revenir sur Paradox : " + server_invite)
client.channels.cache.get(channel_id).send("<#" + memberID + "> Vous avez échoué le test...")
setTimeout(function(){
client.guilds.cache.get(guild_id).members.cache.get(message.author.id).kick()
}, 5000)
} else{
message.channel.send("Réessayer !")
}
}
}
}
}
})
client.login(token);
The database config.json :
{
"bot_token": "TOKEN",
"verification_channelID": "",
"guild_ID": "",
"verification_role_name": "",
"server_invite": "",
"questions": ["eW91IHBhc3NlZA==", "dGhpcyB3YXMgZWFzeQ==", "dGhhbmtzIGZvciBqb2luaW5n", "ZW5qb3kgeW91ciBzdGF5", "dGhhbmtzIGZvciBub3QgYmVpbmcgYW5vbnltb3Vz", "ZW5qb3kgeW91ciBzdGF5", "aW52aXRlIHlvdXIgZnJpZW5kcyE="]
}
You should use:
client.on('guildMemberAdd', member => {
var uname = member.user.username
var disc = member.user.discriminator
var memberID = member.user.id
var rand = Math.random();
rand *= encodingQuestions.length;
rand = Math.floor(rand);
var question = encodingQuestions[rand]
dict[uname] = [Buffer.from(question, 'base64').toString('utf-8'), 3];
const embed = new Discord.MessageEmbed()
.setTitle(uname + "#" + disc)
.setColor(0x1e90ff)
.addField('Welcome', 'Welcome <#' + memberID + '> Déchiffrer le code , vous avez 3 essais ! Utilisez ``&answer {decoded message}`` ', false)
.addField('Question', question, false)
member.send(embed)
member.guild.channels.cache.get(channel_id).send("Welcome <#" + memberID + "> Regarder vos DM pour accédez au serveur !")
});
I updated the embed part, you should use .addField('coucou', 'salut', true);instead of .addField(name='coucou', value='name', inline=true). This is the javascript function parameters syntax.
in my code when I try to put gifs, it runs correctly and works ideally until the gif I select at random doesn't load
module.exports = {
name: "slap",
description: "da un golpe a un usuario",
execute(message, args) {
let userm = message.mentions.users.first();
const user = message.author;
const gif = [
"https://tenor.com/view/mm-emu-emu-anime-slap-strong-gif-7958720",
"https://tenor.com/view/slap-butts-anime-hit-gif-14179582",
"https://tenor.com/view/ass-ass-slap-anime-put-that-ass-away-uzaki-chan-wants-to-hang-out-gif-17851886",
"https://tenor.com/view/hit-hitting-slap-ow-ouch-gif-5497551",
"https://tenor.com/view/anime-boy-bitch-slap-daily-lives-of-high-school-boys-gif-16649188",
"https://tenor.com/view/powerful-head-slap-anime-death-tragic-gif-14358509",
"https://tenor.com/view/oreimo-gif-10937039",
"https://tenor.com/view/overlord-narberal-gamma-anime-slap-gif-18080646",
"https://tenor.com/view/anime-slap-gif-10426943",
"https://tenor.com/view/seiya-cautious-hero-funny-slap-anime-gif-15631717",
"https://tenor.com/view/bunny-girl-slap-angry-girlfriend-anime-gif-15144612",
"https://tenor.com/view/anime-manga-japanese-anime-japanese-manga-toradora-gif-5373994",
"https://tenor.com/view/slap-bakaramon-confused-gif-14866419",
"https://tenor.com/view/konosuba-megumin-yunyun-anime-slap-gif-17555205",
"https://tenor.com/view/asobi-asobase-slap-anime-gif-17190309",
"https://tenor.com/view/slap-anime-gif-9955713",
];
message.replytext = Math.floor(Math.random() * gif.length + 0);
if (!userm) {
const accion2 = [", te dare esto para cumplir tus deseos, masoquista"];
message.unaper = Math.floor(Math.random() * accion2.length + 0);
const embed = new Discord.MessageEmbed()
.addField(user.username + accion2[message.unaper])
.setImage(gif[message.replytext])
.setColor("RANDOM");
message.channel.send({ embed });
}
const accion = [
" le dio una abofeteada a ",
" abofeteo a ",
" dio una dolorosa abofeteada a ",
" abofeteo fuertemente a ",
" sintio la necesidad de abofetear a ",
];
message.dosper = Math.floor(Math.random() * accion.length + 0);
const embed = new Discord.MessageEmbed()
.setAuthor(
user.username + accion[message.dosper] + userm.username,
user.avatarURL({ size: 32 })
)
.setImage(gif[message.replytext])
.setColor("RANDOM");
message.channel.send({ embed });
},
};
The links you are using are not image or gif links but tenor webstite viewing an image. For Each link you'll have to replace it with the actual image.v)
I've been trying to make an RSS reader with JQuery and javascript, but it turns out that javascript doesn't wait for jquery to end before continuing, causing the some registrations to fail.
The console.logs of the example show that the logs of the jquery function are showing up after the logs of the common javascript. This causes the result of the function to change, because it depends on the jquery function.
I'd like to know how to make javascript wait for jquery to end before continuing. The idea is that all of the process marked with ** occur before the "after the calling" log
Here are the logs and the code. Thank you for your help
----Before the calling
**Calling a check_feed
**was there activity: false
----After the calling
----variable result: noact
**judging item0
**hora vs ult_act: 1480805684 > 1480798209 = true
**New message from coyoteazul
**judging item1
**hora vs ult_act: 1480766258 > 1480798209 = false
**judging item2
**hora vs ult_act: 1480743686 > 1480798209 = false
** SHOWS A NOTIFICATION
// #require http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js
function caller(){
console.log("----Before the calling")
var result = check_Feed("https://www.neobux.com/rss/?/601750/", 1480798309)
console.log("----After the calling")
console.log("----variable result: " + result)
}
function check_Feed (FEED_URL, ult_act){
ult_act = parseInt(ult_act)
console.log("**Calling a check_feed")
var titul;
var contador = 0;
var actividad = false;
$.get(FEED_URL, function (data) {
titul = $(data).find("title").first().text();
if (titul == "") {return "F"} //el titulo solo puede estar vacio si el feed esta cerrado
$(data).find("item").each(function () {
console.log("**judging item" + contador)
if (contador < 7){
var el = $(this);
var hora = el.find("pubDate").text()
hora = new Date(hora).getTime()/1000;
console.log("**hora vs ult_act: " + hora + " > " + (ult_act-100) + " = " + (hora > (ult_act-100)))
if (hora > (ult_act-100)){ //solo notifica si la hora supera a la ultima activdad.
var cuerpol = el.children().last().text();
cuerpol = "New message from " + cuerpol;
var linkl = el.find("link").text();
console.log("**"+cuerpol)
setTimeout(function(){ //en firefox si no se muestran a traves de un timeout solo mostrara la 1er notificacion
console.log("** SHOWS A NOTIFICATION");}, 500 * (contador+1))
actividad = true;
}
contador ++;
}
});
});
console.log("**was there activity: " + actividad);
if (actividad)
return "act";
else
return "noact";
}
caller()
A few things before you try out the code below:
jQuery get/post are simple ajax calls that run asynchronously. To
understand them you may start
here
setTimeout also works out in a similar fashion , in essence it executes a function once the time specified elapses.
Try running this code to see the results in the order you are expecting
function caller() {
console.log("----Before the calling")
check_Feed("https://www.neobux.com/rss/?/601750/", 1480798309);
thisGetsPrintedRightAfter();
}
thisGetsCalledAfterEverything = function(result) {
console.log("----After the calling")
console.log("----variable result: " + result)
}
thisGetsPrintedRightAfter = function() {
console.log("This gets printed right after Calling a check_feed");
}
function check_Feed(FEED_URL, ult_act) {
ult_act = parseInt(ult_act)
console.log("**Calling a check_feed")
var titul;
var contador = 0;
var actividad = false;
$.get(FEED_URL, function(data) {
titul = $(data).find("title").first().text();
if (titul == "") {
return "F"
} //el titulo solo puede estar vacio si el feed esta cerrado
$(data).find("item").each(function() {
console.log("**judging item" + contador)
if (contador < 7) {
var el = $(this);
var hora = el.find("pubDate").text()
hora = new Date(hora).getTime() / 1000;
console.log("**hora vs ult_act: " + hora + " > " + (ult_act - 100) + " = " + (hora > (ult_act - 100)))
if (hora > (ult_act - 100)) { //solo notifica si la hora supera a la ultima activdad.
var cuerpol = el.children().last().text();
cuerpol = "New message from " + cuerpol;
var linkl = el.find("link").text();
console.log("**" + cuerpol);
setTimeout(function() { //en firefox si no se muestran a traves de un timeout solo mostrara la 1er notificacion
console.log("** SHOWS A NOTIFICATION");
console.log("**was there activity: " + actividad);
if (actividad)
thisGetsCalledAfterEverything("act");
else
thisGetsCalledAfterEverything("noact");;
}, 500 * (contador + 1));
actividad = true;
}
contador++;
}
});
});
}
caller()