Double quotes within single quote string - NodeJs - javascript

I'm having quite a problem to which other answers pose no solution.
I'm trying to print out double quotes in a string literal. I, however, keep getting errors.
This is the specific function:
app.put('/assignments/:name/assignee/:assignee', function (request, response) {
logic.examine(request, function (mail, jobtitle) {
if (mail !== request.params.assignee && jobtitle.indexOf('Personeel') === -1) {
response.sendStatus(401);
} else {
logs_logic.addLog(mail + ' heeft gebruiker met naam "' + request.params.assignee + '" toegekend aan opdracht met als naam "' + request.params.name + '".');
response.status(200).json(logic.changeAssignee(request.params.name, request.params.assignee));
}
});
});
The error message reads 'Invalid or unexpected token' pointed to the part after the third 'plus' (or concat) sign. So it starts at "toegekend"
Any ideas?
Thanks in advance!

use es6 template literas aka backticks which will create more clarity in statements.
`this is string ${some_variable} more text ${some_variable_2}`
logs_logic.addLog(`${mail} heeft gebruiker met naam " ${request.params.assignee} " toegekend aan opdracht met als naam " ${request.params.name} ".`);

Use backticks (`) to form the string instead of single quotes.
and use
${variable_name}
to use that variable in string.
Here is the example:
logs_logic.addLog(`${mail} heeft gebruiker met naam "${request.params.assignee}" toegekend aan opdracht met als naam "${request.params.name}".`);
Hope this helps.

Give the " literal a try and see if it works for you. Something like this: 'This is "quoted"'

Related

open the mail on outlook using mailto encode problem

Hi In my webpage I generate the information and using mailto for opening the mail on outlook for the user modify the email. It worked fine. However when the body or subject has apostrophe that cause problem, so I used Server.UrlEncode to encode the string. Now, the space show '+' and the new line show '\n'. If I don't use Server.UrlEncode, the function is not called.
There is my code to call the javascript function in vb.net
Dim strSubject As String = Server.UrlEncode(strName)
Dim strBody As String = Server.UrlEncode("it's your order list:" & "\r\n" & strList)
Dim script As String = "MailtoOrder(''," & "'" & strSubject & "', '" & strBody & "')"
If Not Page.ClientScript.IsStartupScriptRegistered(Me.GetType(), "mail") Then
Page.ClientScript.RegisterStartupScript(Me.GetType(), "mail", script, True)
End If
There is my javascript:
function MailtoOrder( to, subject, body) {
var email='';
if (to != undefined) {
email=to;
}
email = email + '&subject=' + encodeURIComponent(subject) + '&body=' + encodeURIComponent(body);
window.location.href = "mailto:" + email;
}
I get away using Server.UrlEncode. I just replace the apostrophe to be escaped character in strSubject and strBody string. it works.

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

Relation fields in ArrowDB Appcelerator

Anyone have knowledge about relations and ArrowDB? I'm adding a User object as an relation field to a Message object, and that works fine. But when I try to add an relation to a File object from the same Message object I get the following error:
400: Failed to send message: Invalid ACS type: file
Anyone have a clue?
Maybe I'm using the wrong notation for the File object!? I've tried: [ACS_File], [ACS_Files] without any luck?....[ACS_User] works like a charm?
Here is my code:
Cloud.Messages.create({
to_ids: to.join(','),
body: 'New Message',
subject: 'Test Message',
custom_fields:
{
"[ACS_File]file_id":videoFile,
"[ACS_User]owner_id":to.join(','),
"pausedAt" : pausedAt,
"correctAnswer": correctAnswer,
"a2" : a2,
"a3" : a3
}
}, function (e) {
if (e.success) {
var message = e.messages[0];
alert('Success:\n' +
'id: ' + message.id + '\n' +
'subject: ' + message.subject + '\n' +
'body: ' + message.body + '\n' +
'updated_at: ' + message.updated_at);
//Her gikk alt bra og melding og video er lastet opp. På tide å sende en push :-)
} else {
alert('Error:\n' +
((e.error && e.message) || JSON.stringify(e)));
}
});
}

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!

Javascript Quotes Problem When Dynamically Adding Content

I'm trying to dynamically add content stored in a variable. However, single quotes are causing problems.
var dynamicelementcode = $("<div id='container'>" + data + "</div>");
dynamicelementcode.prependTo($('#wholecontainer')).hide().fadeIn(300).slideDown(1000);
If the data variable contains a single quote, it breaks my code. How can I solve this problem? The data variable gets its content from a serverside php script.
Any php/js/jquery solution appreciated
Edit:
PHP Code Serverside
$comment_body = "The boy's bicycle";
echo '{ "author": "'.$author.'", "message": "'.$comment_body.'","parentid": "'.$parent_id.'","currentid": "'.mysql_insert_id().'","timestored": "'.$timestampa.'" }';
Jquery Code, Clientside
var newrootcomment = $("<div class='comment'><div class='comment-holder'><div class='comment-body'>"+ data.message + "</div> <abbr class='timestamp' title=''>" + data.timestored + "</abbr><div class='aut'>" + data.author + "</div> <a href='#comment_form' class='reply' id='id"+ data.currentid + "'>Reply</a> </div> </div>");
newrootcomment.prependTo($('#wholecontainer')).hide().fadeIn(300).slideDown(1000);
var dynamicelementcode = $('<div id="container">').text(data)
jQuery text function automatically escapes quotes for you.
UPD. Escaping only single quotes:
var dynamicelementcode = $('<div id="container">').html(data.replace(/'/g,'''))
UPD 2. If you look at the source of your page you'll see something like "message": 'The boy's bicycle' - that's a syntactic error.
Here's a better way to pass PHP data to JavaScript, works with quotes too:
$comment_body = "The boy's bicycle";
echo json_encode(array(
'author' => $author,
'message' => $comment_body,
'parentid' => $parent_id,
'currentid' => mysql_insert_id(),
'timestamp' => $timestamp
));
jQuery already has methods to insert text, you don't need to concatenate strings or take care yourself of escaping. Use the .text() method:
var dynamicelementcode = $('<div id="container"></div>').text(data);
Reference and examples: http://api.jquery.com/text/#text2

Categories

Resources