Example code from Javascript textbook giving unexpected error - javascript

Preface - not relevant to problem
First off I am a noob to Javascript and am in the process of learning it. I have read a lot of Eloquent Javascript but towards the end found it to be too advanced for my level. I was recommended to start reading Professional Javascript for Web Developers by Nicholas Zakas.
Problem
Now I'm attempting to just try and run ObjectTypeExample04.htm which I've included here:
function displayInfo(args) {
var output = “”;
if (typeof args.name == “string”){
output += “Name: “ + args.name + “\n”;
}
if (typeof args.age == “number”) {
output += “Age: “ + args.age + “\n”;
}
alert(output);
}
displayInfo({
name: “Nicholas”,
age: 29
});
displayInfo({
name: “Greg”
});
From what I can understand, it'll just print the object defined in the call to displayInfo and it'll do this through appending the output variable inside that function.
I don't get why I'm getting this error
Exception: SyntaxError: illegal character
when running it in a JavaScript code runner (don't know the technical name). But basically I tried using JSFiddle to no luck and I don't understand what's wrong because I copied and pasted it out of a textbook.

Replace the “ ” symbols with standard " quotes and try it again.

You are using LEFT DOUBLE QUOTATION MARK (“) and RIGHT DOUBLE QUOTATION MARK (”) where you should be using QUOTATION MARK (") (or APOSTROPHE (')).
This is typically caused by writing code using a word processor which automatically replaces straight quotes with typographic quotes instead of a regular text editor.

Replace the "smart quotes" by regular double quotes:
function displayInfo(args) {
var output = "";
if (typeof args.name == "string"){
output += "Name: " + args.name + "\n";
}
if (typeof args.age == "number") {
output += "Age: " + args.age + "\n";
}
alert(output);
}
displayInfo({
name: "Nicholas",
age: 29
});
displayInfo({
name: "Greg"
});

Related

How would I parse multiple or more objects via jQuery?

like so
► add language identifier to highlight code
```python
def function(foo):
print(foo)
► put returns between paragraphs
► for linebreak add 2 spaces at end
► italic or bold
► indent code by 4 spaces
► backtick escapes like _so_
► quote by placing > at start of line
► to make links (use https whenever possible)
https://example.com
example
example
As mentioned by #Pointy there are multiple syntax errors in your code (when accessing the obj array).
But the reason it wouldn't work even after you fix these syntax errors is that the result of your API call is a string and you need to parse it using JSON.parse().
$.get('https://raw.githubusercontent.com/danielhoset27/test1/master/C2RReleaseData.json', function(obj) {
// Parse the received json
const result = JSON.parse(obj);
// Fix the syntax errors
document.writeln(result[0].FFN + " : " + result[0].AvailableBuild);
// Add a line break
document.write('<br />')
// Fix the syntax errors again
document.writeln(result[1].FFN + " : " + result[1].AvailableBuild);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Also consider using Fetch API is your targeted browsers support it.
const appendItem = item => document.body.innerHTML += `<p>${item.FFN} : ${item.AvailableBuild}</p>`;
fetch('https://raw.githubusercontent.com/danielhoset27/test1/master/C2RReleaseData.json').then(response => {
response.json().then(result => {
appendItem(result[0]);
appendItem(result[1]);
});
});
Try This code
$(document).ready(function(){
var url = 'https://raw.githubusercontent.com/danielhoset27/test1/master/C2RReleaseData.json';
$.getJSON(url, function( data ) {
for(var i in data){
console.log(data[i].FFN + " : " + data[i].AvailableBuild)
}
});
});

First character of a string fusionning with a %

So i'm sending a String with javascript to a php page :
if(cp.value!=''){
s+=cp.name +" LIKE '%"+ cp.value +"%'";
console.log(s);
if(sec.value!=''){
s+=" AND "+sec.name+" LIKE '%"+ sec.value +"%'";
console.log(s);
}
}
else{
if(sec.value!=''){disappear
s+=sec.name+" LIKE '%"+ sec.value +"%'";
}
}
console.log(s);
if(s.length!=0){
var connect = new XMLHttpRequest();
connect.onreadystatechange=function(){
if (connect.readyState==4 && connect.status==200){
var resu=connect.responseText;
console.log(resu);
var tab=document.getElementById("main_tab");
tab.innerHTML=resu;
}
};
connect.open("POST","../../Controller/stage.php",false);
connect.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
connect.send("s="+s);
}
}
The string sent is for exemple :
CP_Stage LIKE '%90%' AND secteur_stage LIKE '%ait%'
But when i print the request in the php page i have something like :
SELECT * FROM Stage WHERE CP_Stage LIKE '�%' AND secteur_stage LIKE '%ait%';
i have no idea why my first number disappear with the first %.
If anyone have an idea it would be awesome, thanks !
The percent-sign is a special charcter. Any special characters like %,&,? etc need to be encoded. Your "%90" is converted to an Ascii-Value. You have to encode these values with encodeURIComponent.
s += cp.name + " LIKE '" + encodeURIComponent("%" + cp.value + "%") + "'";
Note that encodeURIComponent does not escape the ' character. If your cp.value has an ' you have to replace it with its encoding value: %27.
By the way.. its a bad idea to send mySQL-queries from client-side - thats a major security flaw. Send only the values and build your queries on server-side.

Unexpected Token Illegal with onclick Java Script in Salesforce.com

I have been working on this most of the morning but to no end. I am trying to execute a button that uses OnClick Java in Salesforce.com and it keeps throwing errors. I think the issue may be with special characters in the data as it works when I simply use just text. But any time numbers or any special characters are present I get the error "unexpected token ILLEGAL". Can anyone help me to see what I am doing wrong and how I can get away from failing when special characters are involved?
{!REQUIRESCRIPT("/soap/ajax/28.0/connection.js")}
var opptyObj = new sforce.SObject("Opportunity");
var caseObj = new sforce.SObject("Case");
var today = new Date();
var sOpptyId = "{!Case.Opportunity__c}";
if( sOpptyId != "")
{
alert("This case is already tied to an opportunity!");
}
else
{
opptyObj.AccountId = "{!Case.AccountId}";
opptyObj.CloseDate = sforce.internal.dateTimeToString(today);
opptyObj.Description="{!Case.Description}";
opptyObj.Case__c = "{!Case.Id}";
opptyObj.Name = "{!Case.Subject}";
opptyObj.StageName = "Estimate in Progress";
opptyObj.Created_from_Case__c = "Y";
opptyObj.Type = "New Business";
opptyObj.Amount = ".01";
var opptyresult = sforce.connection.create([opptyObj]);
if (opptyresult[0].success=='false')
{
alert("Opportunity creation failed: " + opptyresult[0].errors.message);
}
else
{
caseObj.Id = '{!Case.Id}';
caseObj.Opportunity__c = opptyresult[0].id;
caseObj.Status = "Estimate in Progress";
var caseResult = sforce.connection.update([caseObj]);
if(caseResult[0].success == 'false')
{
alert("Case update failed: " + caseResult[0].errors.message);
}
else
{
alert("An opportunity has been created and linked to this case.");
location.reload(true);
}
}
}
Assuming this is some kind of template, whatever is rendering this needs to properly escape some values in the strings it's inserting.
Given this:
opptyObj.Description="{!Case.Description}";
Let's say I enter a description consisting of this:
"That is awesome," said John.
When that is rendered in your template the result is this:
opptyObj.Description=""That is awesome," said John.";
As you might be able to see, the result is a syntax error.
You need to escape quote characters in an text inserted this way. And without knowing what is technology rendering this template I can't give you any specifics, but you want to replace " with \" and ' with \'. The \ escapes characters, forcing them to be treated as literal characters in the string instead of other special meaning.
This must be done as it's being inserted into the script. Something in the spirit of this:
opptyObj.Description="{!Case.Description.replace(/'/, "\\'").replace(/"/, '\\"')}
Exactly how to do that depends on what language or template engine is being used here. But th eresult should look like this:
opptyObj.Description="\"That is awesome,\" said John.";
Ruby on Rails implements an escape_javascript method, which sanitizes data for injection into Javascript. It does the following replacements. It seems like a good baseline.
'\\' => '\\\\'
'</' => '<\/'
"\r\n" => '\n'
"\n" => '\n'
"\r" => '\n'
'"' => '\\"'
"'" => "\\'"
UPDATE:
According to this: http://www.salesforce.com/us/developer/docs/pages/Content/pages_security_tips_scontrols.htm
It looks like you want the JSENCODE function. Something like this, perhaps?
opptyObj.Description="{!JSENCODE(Case.Description)}";

eval javascript function IE6 taking long time

I have the below chunk of code. I've debugged through and located the snippet that is causing a long delay in IE6.
Basically the code loops through a document converting it to XML and sending to a PDF. On Ubuntu and Firefox 4 it takes 3 seconds. On IE it can take up to 40 seconds regularly.
/**
* This function builds up the XML to be saved to the DM.
*/
function getXMLToSave(){
var text="<workbook><sheet><name>Adv4New</name>";
//show_props(document.adv4.row10col1, "document.adv4.row10col1");
for(i=1;i<157;i++){
text = text + "<row number='" + i + "'>";
for(j=1;j<=7;j++){
text = text + "<col ";
//alert(eval('document.adv4.row'+i+'col'+j+'.readonly'));
try{
text = text + "number='" + j + "' label='" + eval('document.adv4.row'+i+'col'+j+'.className')+ "'";
}
catch (e) {
text = text + "number='" + j + "' label=''";
}
try {
if(eval('document.adv4.row'+i+'col'+j).readOnly)
text = text + " type='readonly'";
else
text = text + " type=''";
}
catch (e) {
text = text + " type=''";
}
try {
text = text + " color='" + eval('document.adv4.row'+i+'col'+j+'.style.color') + "'";
}
catch (e) {
text = text + " color=''";
}
text = text + ">";
try {
// don't wrap in a CDATA (like previously), but run cleanNode
// this fixes html entities
var content = eval('document.adv4.row'+i+'col'+j+'.value');
text = text + cleanNode(content);
}
catch (e) {
text = text + "0";
}
text = text + "</col>";
}
text = text + "</row>";
}
text = text + "</sheet></workbook>";
return text;
}
I believe its the eval function causing the delay in IE6. Is there a neat solution to fix this. Thanks very much
Why are you using eval in the firts place?
eval('document.adv4.row'+i+'col'+j+'.style.color')
Use bracket notation!
document.adv4["row"+i+"col"+j].style.color
You don't need eval() at all:
text = text + "number='" + j + "' label='" + document.adv4['row' + i + 'col' + j].className + "'";
Also, in IE6 (but not in newer browsers), building up large strings by repeatedly adding more content is really, really slow. It was way faster in that browser to build up strings by creating an array of substrings and then joining them all together when finished with all the pieces.
Don't use eval EVAL is EVIL. Having said that, you really shouldn't care about IE6: Even MS doesn't support it any longer, why should you bother?
Anyhow, change all eval calls like:
eval('document.adv4.row'+i+'col'+j+'.value');
to
document.adv4['row' + i + 'col' + j].value;
To access the elements directly. Remember that Nodes are objects, so their properties can be accessed either using the dot-notation (foo.bar) or the "associative array" notation: foo['bar'], the latter being very useful when you need the value of a variable to access properties
Don't use eval - period. The eval() should be renamed to evil(). There is almost no situation where you really need to use the eval function.
In this case you can use document.getElementById() to find a DOM node with a specific id.
It's likely that it's all the string concatentation that makes it slow. Each time you add something to the text, it will copy all the previous text into a new string.
Newer browsers have optimised code for this special case, so for them the impact is less.
Instead of concatenating strings like this:
text = text + "something";
use an array instead:
var text = [];
then add items to the array using the push method:
text.push("<workbook><sheet><name>Adv4New</name>");
Finally just join the strings together:
return text.join('');
One solution could be generating a color array (or maybe an object if you need it) and then using it.
But then, ask yourself the question "Should I really support IE6?"

Javascript syntax error

Update: I tried a version of the script without the "beforeContentUpdate" part, and this script returns the following JSON
{"COLUMNS":["TNAME","TBRIEF","GAMEID","TITLEID","RDATE","GNAME","PABBR","PNAME","RSCORE","RNAME"],
"DATA":[["Dark Void","Ancient gods known as 'The Watchers,' once banished from our world by superhuman Adepts, have returned with a vengeance.",254,54,"January, 19 2010 00:00:00","Action & Adventure","X360","Xbox 360",3.3,"14 Anos"]]}
Using the script that includes "beforeContentUpdate," however, returns nothing. I used Firebug to see the contents of the div generated by the tooltip, and it's blank!
Hello, I'm wondering if anyone can help me with a syntax error in line 14 of this code:
The debugger says missing ) in parenthetical on var json = eval('(' + content + ')');
// Tooltips for index.cfm
$(document).ready(function()
{
$('#catalog a[href]').each(function()
{
$(this).qtip( {
content: {
url: 'components/viewgames.cfc?method=fGameDetails',
data: { gameID: $(this).attr('href').match(/gameID=([0-9]+)$/)[1] },
method: 'get'
},
api: {
beforeContentUpdate: function(content) {
var json = eval('(' + content + ')');
content = $('<div />').append(
$('<h1 />', {
html: json.TNAME
}));
return content;
}
},
});
});
});
You forgetting a
+
Should be:
var json = eval('(' + content + ')');
the best for this is www.jslint.com
i'd copied and paste your code and show me this:
Problem at line 21 character 10: Extra
comma.
},
Make sure you JSON has no extra characters, the JSON must be valid. Check how the content returns with a plain alert so nothing will change the string.
Also, consider using parseJSON from jQuery instead of eval. Quote:
var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );
This turned out to be another case where the ColdFusion debugger, when request debugging output is turned on, causes an ajax error. This is one big "gotcha" we need to remember when working with ColdFusion with debugging enabled. It breaks down ajax.

Categories

Resources