how to deal with '&', '(', ')' in javascript - javascript

from my code behind i am passing this to client side script
C# code behind
*note if i comment the below line than i dont get js error.*
if (btnDelete != null)
{
btnDelete.Attributes["onclick"] = String.Format("return DeleteRow('{0}', '{1}', '{2}', '{3}');", e.Row.ClientID, e.Row.RowIndex, DataBinder.Eval(e.Row.DataItem, "Id"), DataBinder.Eval(e.Row.DataItem, "Name"));
}
//javascript
function DeleteRow(rowId, rowIdx, Id, Name) {
var result = confirm('Are you sure you want to delete this record? \n\n Id: ' + Id + "\n Name: " + Name);
if (!result)
HighlightRow(rowId, rowIdx % 2 ? "#DEEEE9" : "#FFFFFF");
return result;
}
error message:
Message: Unterminated string constant
Line: 1280
Char: 180
Code: 0
URI: http://localhost:4964/admin/default.aspx
Message: Unterminated string constant
Line: 1341
Char: 178
Code: 0
URI: http://localhost:4964/default.aspx
Message: Expected ')'
Line: 1401
Char: 152
Code: 0
URI: http://localhost:4964/default.aspx

It's hard to tell from your question, but it sounds like the values that are being returned are including the single quote character (apostrophe) which would end your string in the resulting javascript.
What is the code that is being generated for the lines that are throwing the error?
When similar things have happened to me it resulted in something like:
return DeleteRow('1', '2', 'abscde', 'Mc'Adams');
Which would cause an error because of the value Mc'Adams. If that is the case then you'll have to send your data through a method that escapes values that would otherwise corrupt your javascript.

You've used mixed single and double quotes. Change the line here;
var result = confirm('Are you sure you want to delete this record? \n\n Id: ' + Id + '\n Name: ' + Name)

here is how i abel to fix it:
btnDelete.Attributes["onclick"] = String.Format("return DeleteRow('{0}', '{1}', '{2}', '{3}');", e.Row.ClientID, e.Row.RowIndex, DataBinder.Eval(e.Row.DataItem, "Id"), DataBinder.Eval(e.Row.DataItem, "Name").ToString().Trim().Replace("'", "\\'")));

Related

How do I add <b> (for bolding font) to part of text inside string interpolation for sns message?

I want to take a string in this format I am a level ${level} coder, where ${level} will be some value passed in. But I want only specific word in this sentence bolded. So lets say in this example I want "level" and "coder" bolded. How do I achieve this?
Current Behavior:
Even if I do <b> or <strong> inside `` the tags just get converted to string. It doesn't actually bold the text for me.
Update: This is exactly what I am doing with aws sns. But I want to achieve this with string interpolation.
let snsData = {
Message: < strong > "This is an automated message" < /strong> + '\n' +
"You have successfully uploaded the following:" + '\n'
`File name: ${snsFileName}\n
Number of lines: ${numberOfLines}\n
If there are any issues, please contact XXX for assistance.`,
Subject: 'Successfully Uploaded to XX',
TopicArn: 'XXXXX'
};
Addendum, so this is entirely unique to your instance and I suggest better familiarizing yourself with how string / interpolation and objects work but for the sake of learning, cheers;
const $ = function(id) { return document.getElementById(id) },
level = 'expert',
str = `I am a level <strong>${level} coder</strong>`,
snsFileName = 'testFileNameBlah',
numberOfLines = 99,
snsData = {
Message: '<strong>This is an automated message</strong><br/>' +
'You have successfully uploaded the following:<br/>' +
`File name: <strong>${snsFileName}</strong><br/>
Number of lines: <strong>${numberOfLines}</strong><br/>` +
'If there are any issues, please contact XXX for assistance.<br/>',
Subject: 'Successfully Uploaded to XX',
TopicArn: 'XXXXX'
};
$('blah').innerHTML = str + '<hr>';
$('fixme').innerHTML = snsData.Message + snsData.Subject;
<span id="blah"></span>
<h2>Addendum</h2>
<p id="fixme"></p>

Two similar SQLite case statements, one works, the other does not

The first statement works, the second comes back with the error below. The strange thing is except for variable names, they are the same statement, so if one works, the other should work as well.
"Error: SQLITE_ERROR: no such column: RAF60"
Where RAF60 is my data. I thought that I may have a quote in the wrong place as it's trying to read my data as a column but can't see it, also looked for somewhere I may have swapped my data with an expression, but could not see that either.
The RFID1,2,3 and the CarPlates1,2,3 are formatted as text
Statement one exactly as it appears below.
msg.topic = 'SELECT "RFID1", "RFID2", "RFID3", case when "RFID1" = ' + readrfid + ' then RFID1 when "RFID2" = ' + readrfid + ' then RFID2 when "RFID3" = ' + readrfid + ' then RFID3 else null end dbrfid FROM SiteDB'
The output below from Node-Red, I reformatted it to make it easily readable. It shows that the data is populating the right fields and this code works. Its the above statement with the data inserted, just prior to being sent to SQLite
topic:
"SELECT "RFID1", "RFID2", "RFID3", case
when "RFID1" = 149544749819338 then RFID1
when "RFID2" = 149544749819338 then RFID2
when "RFID3" = 149544749819338 then RFID3
else null
end dbrfid FROM SiteDB"
payload: "149544749819338"
_msgid: "232263a1.02d34c"
_event: "node:ad044b82.8c419
0: object
Statement two, the sql query exactly as it appears below
msg.topic = 'SELECT "CarPlate1", "CarPlate2", "CarPlate3", "dbcarplate", case when "CarPlate1" = ' + readlpr + ' then CarPlate1 when "CarPlate2" = ' + readlpr + ' then CarPlate2 when "CarPlate3" = ' + readlpr + ' then CarPlate3 else null end dbcarplate FROM SiteDB
The output below from Node-Red, I reformatted it to make it easily readable. It also shows that the data is populating the right fields, but comes back with an error message, the statement below is the data just before its sent to SQLite
topic: "SELECT "CarPlate1", "CarPlate2", "CarPlate3", "dbcarplate", case
when "CarPlate1" = RAF60 then CarPlate1
when "CarPlate2" = RAF60 then CarPlate2
when "CarPlate3" = RAF60 then CarPlate3
else null
end dbcarplate FROM SiteDB"
payload: " RAF60 "
_msgid: "f2831f05.42c24"
_event: "node:61abb27f.bc684c"
It does not run in SQLite, and I get the error message.
"Error: SQLITE_ERROR: no such column: RAF60"

LineBreak in console object

Line break in javascipt string console
console.log("Foo" + "\n" + "Bar");
Line break in javascript object console
console.log({ value : "Foo\nBar" });
Is it possible to add linebreaks in javascript objects.
The answer is no: when you print an object to the console log, strings will be written as javascript objects (similar but not identical to what you'd get if you explicitly converted them into JSON, like console.log(JSON.stringify(object))).
If you want for some reason to print your strings with line breaks, you'd have to implement the object-to-string conversion yourself; perhaps with something like this:
function customString(object) {
let string = '{\n';
Object.keys(object).forEach(key => {
string += ' "' + key + '": "' + object[key] + '"\n';
});
string += '}';
return string;
}
console.log(customString({ value: "Foo\nBar" }));
(It sounds like you have an idea in mind of exactly how you want this output to look, so adjust the function above until it works as expected.)
You can make JSON pretty with automatic line breaks using:
console.log(JSON.stringify({ test: { key: { inner: 'val' } }}, null , 2))
Where 2 is the number of spaces/indent for each level.
You can use ES6:
console.log(`hello
world`)
will produce:
hello
world
I think its originally creating a line break, but due to the object, it's not showing directly. Try to assign it in variable and access that in the console.
Code:
var v = {val:"test\ntest"};
console.log(v.val);
Output:
test
test

Send an array of objects from JS/TS (Angular 2) to WCF?

i have to send an array of objects like this
[{"Cod":"1"},{"Cod":"5"}]
to my C# WCF Service which i used until today without problems with wsHttpBinding (so no JSON using here, only XML).
The request, POST, contains this param:
let param = "<cod>" + data + "</cod>";
My problem is on WCF because i can't find a way to get that array of objects from the parameter of the method:
public string GetArrayOfObjects(CompositeType[] cod)
{//implementation not important because i can't enter here...}
where CompositeType is:
[DataContract]
public class CompositeType
{
string cod;
[DataMember]
public string Cod
{
get { return cod; }
set { cod = value; }
}
}
I have tried so many things like changing the parameter to:
Object[] cod
List<string> cod
...
Everytime i get this error (translating):
Exception generated by the formatter in an attempt to deserialize the message: Error trying to deserialize the parameter http://tempuri.org/:cod. InnerException: 'Error at line 1 position 341. Expected status 'Element' .. Found 'Text' with '' name space ''. '.
...
This is the post message that i'm sending:
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<s:Envelope xmlns:a=\"http://www.w3.org/2005/08/addressing\" xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\">" +
"<s:Header>" +
"<a:Action s:mustUnderstand=\"1\">http://tempuri.org/IService1/" + GetArrayOfObjects + "</a:Action>" +
"</s:Header>" +
"<s:Body>" +
"<" + GetArrayOfObjects + " xmlns=\"http://tempuri.org/\">" +
param +
"</" + GetArrayOfObjects + ">" +
"</s:Body>" +
"</s:Envelope>";
where param is defined before. The JSON.stringify of data inside param gives the first example of this question ([{"Cod":"1"},{"Cod":"5"}]). This post message was always fine with single value params.
Some sites show a solution with a json deserializer on wcf, but i'm using XML...it's not an option right now to re-implement the project in json.
I tried for one day but i didn't find a solution, i'd love to hear some solutions from you! Thanks to all.

Uncaught Syntax Error: Unexpected token - Cloud Code Parse save function

Situation - looping over array of events and assigning properties from JSON parsed
Expected outcome - upload to Parse cloud storage
APIs that I'm using -
https://www.eventbrite.com/developer/v3/formats/event/#ebapi-std:format-event
https://www.parse.com/docs/js/guide
I'm new to Javascript (there actually might be more than one syntax error)
I don't know why I get this error on line 83 when trying to deploy to Parse Cloud Code
What I'm passing in -
var cities = ["San Francisco", "London"];
eventsArray = JSON.parse(httpResponse.text)["events"];
loopEvents(eventsArray);
the whole function as screenshot (syntax highlighting for readability) --> code
the function as text -->
function loopEvents(events) {
if (j == cities.length) {j=0};
for (var i = 0; i < events.length; i++) {
//Parse.Cloud.useMasterKey(); is not needed ATM I think
console.log("assigning properties for " + cities[j] + ".");
list.save({ // saving properties
number: String(i); // ****THIS IS THE LINE 83****
uri: events[i]["resource_uri"];
url: events[i]["url"];
id: events[i]["id"];
name: events[i]["name"]["text"];
description: events[i]["description"]["text"] || "None provided.";
status: events[i]["status"];
capacity: String(events[i]["capacity"]);
logo: events[i]["logo_id"]["logo"] || "http://www.ecolabelindex.com/files/ecolabel-logos-sized/no-logo-provided.png";
start: moment(events[i]["start"]["utc"]);
end: moment(events[i]["end"]["utc"]);
online: events[i]["online_event"];
currency: events[i]["currency"];
ticketClasses: events[i]["ticket_classes"] || "It's freeee!";
ticketClassesNames: events[i]["ticket_classes"]["name"] || "None provided.";
ticketClassesCost: events[i]["ticket_classes"]["cost"] || "It's freeee!";
ticketClassesDescription: events[i]["ticket_classes"]["description"] || "None provided.";
}, {
success: function(list) {
console.log("RIP CloudCode, we had good times!");
},
error: function(list, error) {
console.log("u fuc*ed up, with error: " + error.text + ", son.");
}
});
}
j++;
}
maybe it's all wrong, appreciate the effort and constructive answers ;))) if you need any other info just comment bellow and I'll edit.
EDIT.1 - after replacing ; for , I get the following error
As you're using object, semi-colon ; is not valid syntax.
Remove ; from all the lines inside the object.
number: String(i);
// ^
Use , comma instead.
number: String(i),
// ^
Code
// Notice the comma at the end of each element
list.save({ // saving properties
number: String(i),
uri: events[i]["resource_uri"],
url: events[i]["url"],
id: events[i]["id"],
name: events[i]["name"]["text"],
description: events[i]["description"]["text"] || "None provided.",
status: events[i]["status"],
capacity: String(events[i]["capacity"]),
logo: events[i]["logo_id"]["logo"] || "http://www.ecolabelindex.com/files/ecolabel-logos-sized/no-logo-provided.png",
start: moment(events[i]["start"]["utc"]),
end: moment(events[i]["end"]["utc"]),
online: events[i]["online_event"],
currency: events[i]["currency"],
ticketClasses: events[i]["ticket_classes"] || "It's freeee!",
ticketClassesNames: events[i]["ticket_classes"]["name"] || "None provided.",
ticketClassesCost: events[i]["ticket_classes"]["cost"] || "It's freeee!",
ticketClassesDescription: events[i]["ticket_classes"]["description"] || "None provided."
}, {
See Object creation
ticket classes is actually an array and to access it I had to add a expand parameter to the httpRequest, other than that the code itself was fine, thx Tushar for the syntax correction.

Categories