ajax strange error with sending multiple parameter - javascript

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.

Related

Correctly usage of vars in 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.

Firefox add wrong extention to OpenXML spreadsheet file with supposed good MIME type

I'm creating a webpage that uses the script FileSaver.js (https://github.com/eligrey/FileSaver.js) to make the user download an OpenXML file.
Here is the function that download the file using Ajax, decompress it and then make the user download it:
function dlExcel(){
var bOk = true;
try {
var isFileSaverSupported = !!new Blob;
} catch (e) {
bOk = false;
alert("Votre navigateur ne supporte pas l'expore des fichiers excel, veuillez le metre à jour.");
}
var oReq = new XMLHttpRequest();
oReq.open("GET", "AJXExcel.aspx", true);
oReq.responseType = "arraybuffer";
oReq.onload = function (oEvent) {
if (oReq.status == 503){
alert("Une erreur est survenue");
}
else if (oReq.status == 208){
alert("Le fichier demandé comporte trop de ligne, veuillez affiner votre recherche à l'aide des filtres poposé");
}else{
var arrayBuffer = new Uint8Array(oReq.response);
var gunzip = new Zlib.Gunzip(arrayBuffer);
var plain = gunzip.decompress();
var blob = new Blob([plain], {
"type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
});
if(oReq.status == 206)
alert("Le fichier généré comportait trop de lignes, il a donc été tronqué");
saveAs(blob,"resultats.xml");
}
document.getElementById("ctl00_ctl00_MenuContentPlaceHolder_MainContentPlaceHolder_loading").style.display = "none";
document.getElementById("ctl00_ctl00_MenuContentPlaceHolder_MainContentPlaceHolder_param").style.display = "block";
}
if (bOk){
oReq.send(null);
}
}
I have tried many MIME Type and extension and they either open using the XML Editor (the soft from office that determines with soft to use to open the XML File) or directly with Excel (which I want) but Firefox adds a .xls after the .xml so that make a file.xLs.xml that excel refuse to open.
I wasn't able to find a similar issue on the web, so if I could at least have an idea on what's causing it I'll be grateful!
I was thinking of the Windows registry at first, but the issue appears to only happen on Firefox so.
I found a similar post here Firefox add wrong extention to OpenXML spreadsheet file with supposed good MIME type.
It looks like a reported bug.
Although this glitch doesn't seem confirmed yet.
But you cant try with the mime type vdn.application/xml.

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);

Parsing output of textarea in Javascript

I have a HTML form with a textarea in it.
When entering a text with some enters in it, my Javascript malformes and wont load.
The forms submits to a PHP script that outputs the javascript below.
How can I fix this?
function confirmsms() {
var redirect = confirm("Er zullen 791 smsjes worden verzonden, klik op OK om door te gaan");
if (redirect == true) {
window.location.href = 'send.phpregio=%&vakgebied=Loodgieter&disciplines=&bericht=aasdasd
asdasda
sdasdasd';
}
}
</script>
Change to this:
function confirmsms() {
var redirect = confirm("Er zullen 791 smsjes worden verzonden, klik op OK om door te gaan");
if (redirect == true) {
window.location.href = 'send.php?'
+ 'regio=%&vakgebied=Loodgieter&disciplines=&'
+ 'bericht=aasdasdasdasdasdasdasd';
}
}
UPDATE: It seems that your php variable $b‌​ericht has line returns in it. Let's sanitize the variable to remove spaces and line returns like so:
$bericht = str_replace(array(' ', "\n", "\t", "\r"), '', $bericht);
Then you can use your code as before. To be safe, I would sanitize all your php variables that are going to be dropped right into javascript.
<HTML>
<HEAD>
<script type=\"text/javascript\">
function confirmsms() {
var redirect = confirm(\"Er zullen $count smsjes worden verzonden, klik op OK om door te gaan\");
if (redirect == true) {
window.location.href = 'send.php?regio=$regio&vakgebied=$vakgebied2&disciplines=$disciplines&bericht=$b‌​ericht'; }
}
Looks like the problem is you are not encoding your URL! As in your problem you are passing data using GET method your data will be the part of the URL itself!
Simply use encodeURI() before sending! So your code should look like
function confirmsms() { var redirect = confirm("Er zullen 791 smsjes worden verzonden, klik op OK om door te gaan"); var encodedValue = encodeURI("YOUR TEXTAREA VALUE HERE"); if (redirect == true) { window.location.href = 'send.php?VAR1=VAL1&VAR2=VAL2'; }}
And at the back-end you can decode URL using string urldecode ( string $str )
Hope you this is what you are looking for!

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);

Categories

Resources