Correctly usage of vars in javascript - javascript

How can I use these both scripts on the same page? I'm new in js but I'm pretty sure that I can't use these same vars to make both scripts work correctly after an error (or even more if I want to). "Swal" is a customized alert.
<script>
window.onload = function(){
var url = new URL(window.location.href);
var error = url.searchParams.get("error");
if(error==1) swal("Oops...", "Primeiro você deve escolher uma foto. Clique no botão 'Alterar Foto'.", "error");
}
</script>
<script>
window.onload = function(){
var url = new URL(window.location.href);
var error = url.searchParams.get("error");
if(error==2) swal("Formato Inválido", "Por favor, escolha uma imagem no formato 'PNG' ou 'JPG'.", "warning");
}
</script>

You could merge them together like :
<script>
window.addEventListener('load', function() {
var url = new URL(window.location.href);
var error = url.searchParams.get("error");
if(error==1) {
swal("Oops...", "Primeiro você deve escolher uma foto. Clique no botão 'Alterar Foto'.", "error");
} else if(error==2) {
swal("Formato Inválido", "Por favor, escolha uma imagem no formato 'PNG' ou 'JPG'.", "warning");
}
}
</script>
NOTE: It will be better to use addEventListener to attach events instead of onload.

Don't use the old onload/onclick, use addEventListener and/or attachEvent if you need to support < IE9.

Related

I can't show content of a list of items on my div

I have a class (ignicoes) that has a list as one attribute, that list cointains other attributes like dispositivo, latitude, longitude etc. I want to get the contents of that list and show them on my div. However when I run the code bellow nothing is showing. When I do console.log(ocorrencia.dispositivo), it returns nothing. What do you think is the error?
Here is was I have so far:
function getData() {
$.get(`/api/IgnicoesAPI/8020`, function (data) {
//o div terá que ser limpo para que a informação não seja subreposta
document.getElementById("myDiv").innerHTML = "";
$('#myDiv').append(data.latitude);
var lista = data.listaOcorrencias;
$.each(lista, function (ocorrencia, o) {
console.log(ocorrencia.dispositivo);
});
});
}
Here is what the variable data is returning:
Here is what is showig when I run the code:
Try this.
function getData() {
$.get(`/api/IgnicoesAPI/8020`, function (data) {
//o div terá que ser limpo para que a informação não seja subreposta
document.getElementById("myDiv").innerHTML = "";
$('#myDiv').append(data.latitude);
var lista = data.listaOcorrencias;
$.each(lista, function (ocorrencia, o) {
$.each(ocorrencia, function (ocorrencia_1, o) {
console.log(ocorrencia_1.dispositivo);
});
});
});
}
function getData() {
$.get(`/api/IgnicoesAPI/8020`, function (data) {
//o div terá que ser limpo para que a informação não seja subreposta
document.getElementById("myDiv").innerHTML = "";
$('#myDiv').append(data.latitude);
var lista = data.listaOcorrencias;
$.each(lista, function (ocorrencia, o) {
console.log(lista[ocorrencia].dispositivo);
});
});
}
Does this work for you ? I'm not sure if the data you are receiving needs to be parsed before your use it or not :)

google app scripts ignoring if statement

I have 2 google forms that record form responses to a google Spreadsheet File. Each form delivers the answers to its respective sheet or "tab".
I have written a script for each form that sends me an email whenever the form is submitted. I have tested them separately and they work. However, when I try to put them together, neither the sorting or the sending of the email work.
I am having a hard time debugging because the main function is run by a trigger and I use form response data in my script and thus cannot execute the function manually.
Code:
//this function is called every time a form is submitted
function procesarVinculacionORetiro(e){
//decide which of the two forms were submitted:
if (e.namedValues["Ingresa por?"]){
/////////
//////// VINCULACIONES
///////
//ordenar hoja de vinculaciones
//enviar correo con info ultima vinculacion
//sort data so new is always on top
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Vinculaciones');
var range = sheet.getRange("A2:X");
//column A = 1, B = 2, etc.
range.sort( { column : 1, ascending: false } );
//**********
//PARA EL CORREO, CALCULEMOS DATOS IMPORTANTES:
//**********
//esto arregla el problema de emails duplicados
Utilities.sleep(3000);
//e es un objeto que contiene la info del formato que acaban de submit
var dataset = e.values;
var timestamp=e.namedValues["Timestamp"];
var ingresaPor=e.namedValues["Ingresa por?"];
var cualTienda=e.namedValues["En cual tienda? o en oficina?"];
var cargo=e.namedValues["Que cargo va a desempeñar?"];
var nombreEmpleado=e.namedValues["Nombre de la persona a vincular? (OJO: sin apellidos)"];
var apellido1Empleado=e.namedValues["Apellido #1 de la persona a vincular?"];
var apellido2Empleado=e.namedValues["Apellido #2 de la persona a vincular?"];
var quienSolicita=e.namedValues["Como te llamas tu?"];
var quienAutoriza=e.namedValues["Quien lo autoriza?"];
//*********
//CONFIGUREMOS EL CUERPO DEL CORREO
//*********
var message='';
message="Hola Equipo, hay una nueva vinculacion pendiente por crear. Los datos completos estan en la hoja de Vinculaciones.<br/><br/> RESUMEN: <br/><br/> fecha de reporte: "+timestamp+"<br/> nombre: "+nombreEmpleado+" "+apellido1Empleado+" "+apellido2Empleado+"<br/>ingresa por: "+ingresaPor+"<br/>reportado por: "+quienSolicita+"<br/> dice que lo autoriza: "+quienAutoriza+"<br/>"
//configuremos header correo:
var destinatario='pamunoz#azucarcolombia.com';
//cuadremos cc
var carbonCopy='nomina#grupoimperio.com.co, jerodriguez#azucarcolombia.com, imalca#azucarcolombia.com';
var subject="#Vincular para "+cualTienda+" (" +cargo+"): "+ nombreEmpleado+" "+apellido1Empleado+" x "+ingresaPor + " x " + quienSolicita
MailApp.sendEmail({
to: destinatario,
cc: carbonCopy,
subject: subject,
htmlBody: message,
replyTo: 'nadie#azucarcolombia.com'
});
}
else {
/////////
//////// RETIROS
///////
//sort data so new is always on top
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Retiros');
var range = sheet.getRange("A2:I");
//column A = 1, B = 2, etc.
range.sort( { column : 1, ascending: false } );
//**********
//PARA EL CORREO, CALCULEMOS DATOS IMPORTANTES:
//**********
//esto arregla el problema de emails duplicados
Utilities.sleep(3000);
//*********
//CONFIGUREMOS EL CUERPO DEL CORREO
//*********
var message='';
message="Hola Equipo, hay un nuevo retiro pendiente, lo pueden ver en la hoja RETIROS. Favor gestionar pago liquidacion en cuanto antes. Gracias"
//configuremos header correo:
var destinatario='pamunoz#azucarcolombia.com';
//cuadremos cc
var carbonCopy='nomina#grupoimperio.com.co, jerodriguez#azucarcolombia.com, imalca#azucarcolombia.com';
var subject='#Retiro Nuevo';
MailApp.sendEmail({
to: destinatario,
cc: carbonCopy,
subject: subject,
htmlBody: message,
replyTo: 'nadie#azucarcolombia.com'
});
}
}

Javascript SyntaxError: missing ; before statement

I'm looking for integrate a post-it application in my django website with Javascript/JQuery.
I found something as a tutorial and I tried to insert it in my script but I get SyntaxError :
SyntaxError: missing ; before statement post-it.js:2:19
I don't know Javascript langage so it's a bit complicated for me, but I don't see where ; is missing :/
This is my HTML post-it part :
<h1>Post-It</h1>
<input type="button" value="Ajouter un Post-It" id="btn-addNote" />
<div id="board"></div>
This is my Javascript file :
(function ($, $S) {
// $jQuery
// $S window.localStorage
// Déclaration des variables
var $board = $('#board'),
// Placement des Post-It
Postick, //Object Singleton contenant les fonctions pour travailler sur le LocalStorage
len = 0,
// Nombre d'objets dans le LocalStorage
currentNotes = »,
// Stockage du code HTML de l'élément Post-It
o; // Données actuelles du Post-It dans le localStorage
// Gérer les Post-It dans le LocalStorage
// Chaque objet est enregistré dans le localStorage comme un Object
Postick = {
add: function (obj) {
obj.id = $S.length;
$S.setItem(obj.id, JSON.stringify(obj));
},
retrive: function (id) {
return JSON.parse($S.getItem(id));
},
remove: function (id) {
$S.removeItem(id);
},
removeAll: function () {
$S.clear();
},
};
// S'il existe des Post-It on les créer
len = $S.length;
if (len) {
for (var i = 0; i < len; i++) {
// Création de tous les Post-It se trouvant dans le localStorage
var key = $S.key(i);
o = Postick.retrive(key);
currentNotes += '<div class="postick"';
currentNotes += ' style="left:' + o.left;
currentNotes += 'px; top:' + o.top;
// L'attribut data-key permet de savoir quelle note on va supprimer dans le localStorage
currentNotes += 'px"><div class="toolbar"><span class="delete" data-key="' + key;
currentNotes += '">x</span></div><div contenteditable="true" class="editable">';
currentNotes += o.text;
currentNotes += '</div></div>';
}
// Ajoute tous les Post-It sur le tableau de bord
$board.html(currentNotes);
}
// Dès que le document est chargé, on rend tous les Post-It Draggable
$(document).ready(function () {
$(".postick").draggable({
cancel: '.editable',
"zIndex": 3000,
"stack" : '.postick'
});
});
// Suppression du Post-It
$('span.delete').live('click', function () {
if (confirm('Etes vous sûr de vouloir supprimer cette note ?')) {
var $this = $(this);
// L'attribut data-key permet de savoir quelle note on va supprimer dans le localStorage
Postick.remove($this.attr('data-key'));
$this.closest('.postick').fadeOut('slow', function () {
$(this).remove();
});
}
});
// Création du Post-It
$('#btn-addNote').click(function () {
$board.append('<div class="postick" style="left:20px;top:70px"><div class="toolbar"><span class="delete" title="Fermer">x</span></div><div contenteditable class="editable"></div></div>');
$(".postick").draggable({
cancel: '.editable'
});
});
// Sauvegarde tous les Post-It lorsque l'utilisateur quitte la page
window.onbeforeunload = function () {
// Nettoyage du localStorage
Postick.removeAll();
// Puis on insère chaque Post-It dans le LocalStorage
// Sauvegarde la position du Post-It, afin de le replacer lorsque la page est chargée à nouveau
$('.postick').each(function () {
var $this = $(this);
Postick.add({
top: parseInt($this.position().top),
left: parseInt($this.position().left),
text: $this.children('.editable').text()
});
});
}
})(jQuery, window.localStorage);
Thank you :)
PS : I thing that the SyntaxError comes from there right : currentNotes = »,
Protip: When developing, keep indentations cool. You indentation here is a mess and is difficult to follow code blocks. I know you are new so don't worry, but just get used to have a clean indentation.
Now, if you get the code and run it, elsewhere (Chrome console, jsfiddle or whatever) it tells you the exact line where the error is happening, as is a SyntaxError and that kind of errors happens when the engine is checking the code, but not running it, so is not needed to have all the needed libs loaded along with the code.
If you check this fiddle: http://jsfiddle.net/8now04xs/1 In the console you will notice that the error comes from the line 54, and if you click on it (Being in CHrome DevTools) it will lead you directly to the line with the problem: http://i.imgur.com/G8tPl92.gifv
You were right, the error code comes from the line you said. The problem is that is not a string, nor a number or a valid keyword. Is a non-valid character.
I don't read all the code, but I guess that you want it to be a string. In JavaScript (and almost all languages), strings must be quoted with either single or double quote, like this:
currentNotes = "»",
If you look around the rest of the code, you will se a lot of strings following this pattern, so you can understand better how this works. If you want it to be an empty string then you have to it right this:
currentNotes = "",
If you look closely, it makes sense.
After fixing this error, the fiddle will fail, as it will try to run the code and encounter a lot of problems because not running in your Django environment.
I check your code on jshint.
There is 2 problem.
1 . Quote '»' [I already mention about this on comment.]
Missing ;
}; // Missing ; in this line.
})(jQuery, window.localStorage);

Multiple alert dialog on Android app

I'm developing a cross platform application using Appcelerator Titanium.
I'm going to fire logout method when user clicks Android back button, in the next windows after login window.
Everything works, but the second time I tried to login and then logout alert dialog shows up two time.
Hope someone will help. Giacomo.
var win = Titanium.UI.currentWindow;
var msg = Titanium.UI.createLabel({
text:"Mail: " + win.email + "\nNome: " + win.name,
top:10,
left:10,
width:300,
height:'auto'
});
win.add(msg);
//definisco una finestra di dialogo per informare l'utente sul logout
var dialog = Ti.UI.createAlertDialog({
buttonNames: ['Si', 'No'],
message: 'Vuoi effettuare il logout?',
title: 'Attenzione'
});
//intercetto il tasto indietro di android e gestisco il Logout
var listener = win.addEventListener('android:back',function(e){
//aggiungo un event listener alla finestra di dialogo intercettando il tasto si o no
dialog.show();
dialog.addEventListener('click', function(e){
if (e.index == 1){
//è stato cliccato il tasto NO, quindi nessuna azione
}else if(e.index == 0){
//è stato cliccato il tasto Si, quindi effettuo il logout, cancello la variabile di sessione ...
win.close();
win.remove(msg);
win.remove(dialog);
}
});
});
I have pulled your answer out of the question and posted it here. This will allow future users to more easily see your solution.
The solution end up being this code
var handlerBack = function (e){
//aggiungo un event listener alla finestra di dialogo intercettando il tasto si o no
dialog.show();
dialog.addEventListener('click', function(e){
if (e.index == 1){
//è stato cliccato il tasto NO, quindi nessuna azione
}else if(e.index == 0){
//è stato cliccato il tasto Si, quindi effettuo il logout, cancello la variabile di sessione ...
win.close();
win.remove(msg);
win.remove(dialog);
win.removeEventListener('android:back', handlerBack);
}
});
};
win.addEventListener('android:back', handlerBack);

ajax strange error with sending multiple parameter

please check with me where is the error in this ajax code to send 2 parameters:
var xhr = getXhr();
// On défini ce qu'on va faire quand on aura la réponse
xhr.onreadystatechange = function(){
// On ne fait quelque chose que si on a tout reçu et que le serveur est ok
if(xhr.readyState == 4 && xhr.status == 200)
{
selects = xhr.responseText;
// On se sert de innerHTML pour rajouter les options a la liste
//document.getElementById('prjsel').innerHTML = selects;
}
};
xhr.open("POST","ServletEdition",true);
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
id=document.getElementById(idIdden).value;
fu=document.getElementById("formUpdate").value;
//alert(fu);
var i=1;
xhr.send("id=" +id+", fu="+i);
i cant got the value of fu i don't know why.
thanks
The contents of your xhr.send() need to be URL encoded. For example:
xhr.send("id=1&fu=2");
Basicallly, anything that goes inside the xhr.send() would be the same as the query string you'd set with a GET. In other words, what you have inside send should also work on the end of a URL:
http://www.mysite.com/path/to/script?id=1&fu=2
it is really strange because i am used to work with it like that.
so i changed to the next:
xhr.send( "id="+id+"&fu="+i);
and it works.
thanks for help.

Categories

Resources