Javascript Uncaught Syntax error caused due to passing of variable - javascript

I am trying to pass a few variables from my php to the javascript and its working fine except for when I add a particular variable to the function call. There are 3 variables being passed all of which are related to a youtube video. the ID is being retrieved from a database, and the other two (title and description) are being retrieved using the ID from the youtube api.
<a href="#" class="list-group-item" id="{{$vidID[$i]}}" onclick="updateVid('{{$vidID[$i]}}', '{{$title[$i]}}', '{{$desc[$i]}}test')">
I am using hogan templating so the {{}} is the same as php tags with an echo. The problem only seems to occur when I add in the description variable to the call. Without it, the other two work perfectly fine. After doing some research it seems this is caused by an invisible character but I retyped my code to make sure and my code wasn't the problem. The developer console shows that problem is occurring on the last line of the description variable so it seems that the description is being retrieved with an invisible character from the api. I am just trying to do a simple alert with the description in the js function. How can I get rid of this character?

Without seeing the actual values, the most obvious problem would be that characters in your content are breaking the html and / or the javascript function call.
Echoing variables directly in html like that is a bit tricky as you need to escape for the javascript but also for the html. In this case you can probably use:
... '{{htmlspecialchars(json_encode($desc[$i]), ENT_QUOTES)}}test' ...
The json_encode call will probably get you an extra pair of double quotes around the string.
However, note that the best way to get your variables to javascript is to do that directly in a script block - without html in the middle - using json_encode in php. Then you can be sure any data can be passed without problems and you can decode it in javascript to get your structure back (in case of arrays and objects).

Related

Stop "encodeURIComponent" from converting HTML break into carriage return symbol

I am in the process of creating a forum. I am doing this without tutorials to test my php, mysql, javascript knowledge and it's going well however I've encountered 1 problem:
I am using encodeURIComponent() to sanitise the posted forum text before sending it via ajax to my PHP and finally through to MySQL. I've noticed that this changes any new lines into the literal carriage return symbol (down and left arrow).
When this forum text is then returned from the database through an ajax request I can see this symbol in my console window but the javascript simply ignores it.
How can I make it recognise this symbol?
Image of the console window
Image of the output HTML
HTML is always ignoring carriage returns, because you are meant to use <p></p> and <br/> for that.
The easiest way to fix your issue is to just replace all carriage returns with line breaks again. You can use str_replace with PHP or str.replace with JavaScript.

Why is this masked JS code in a GET parameter: '*alert(13)*' executed on my page?

We had a WhiteHat scan done of our site, and one of the vulnerabilites they returned was our URL appended with whscheck'*alert(13)*'a/. When we run the full URL (https://oursite.com/phorders3/index.php/whscheck'*alert(13)*'a/), the site loads and an alert with the value of 13 pops. Can anyone explain how this works? What exactly are the asterisks and the a/ doing?
The code in your page is using the value from the URL in a string literal in the Javascript, without escaping the value properly. That means that anyone can just put Javascript in the URL and it will execute in the page.
That could for example be used for cross site scripting by linking to your site with such an URL, and when someone uses the link the script will run in their browser, pick up some information that is private to that user and send it somewhere.
The apostrophes and the asterisks are used to break out of a string literal. If you have some code like this in the Javascript in the page:
var s = '<? echo $variable ?>';
where the variable contains the value from the URL, it would end up like this in the rendered page:
var s = 'whscheck'*alert(13)*'a';
The apostrophe makes the string literal end, and makes the following expression a part of the Javascript code instead of content in a string.
The asterisk is just an operator between the expressions. It's easier to put in an URL than the + operator that would otherwise be a natural choise.
More than likely this injection is landing somewhere between script tags () and the URL is being reflected in some sort of function or variable inside the script. Here is a breakdown of the injection and how/why it works.
' breaks out of the string literal in the variable definition
* causes the javascript to focus on that portion of code first and is often a way of getting around filters that disallow ;
alert(13) is the proof of concept that causes the alert box with 13 inside to show execution of javascript
* again is more than likely to bypass a filter or WAF blocking ;
' to re-open the string literal to make the syntax of the javascript correct
a is just some arbitrary input to go into the string
/ is to close off the path of the URL itself in what appears to be a RESTful URL structure.
There is an option in the Sentinel interface for you to ask the Whitehat engineers these kinds of questions directly, which is a very helpful resource.

PHP to JS: printing js variable (like PHP echo) compatible with AJAX responseText?

I'm using W3 Schools' AJAX PHP Example (http://www.w3schools.com/ajax/ajax_aspphp.asp) as the foundation for my guestlist web app that uses data stored in LocalStorage, rather than MySQL database, in order for users to be able to search while offline. Now I'm trying to finalize the search guest part.
This is how it works (and differs from the example above):
(index.php). Placing / mirroring all records from MySQL db into
javascript arrays
(index.php). Storing the above mentioned js arrays in LocalStorage
(index.php). By using the AJAX GET code used in the example,
sending the searched item to getData.html (a html file instead of
php file as W3 does)
(getData.html). Successfully getting the searched item through the
URL parameter
(getData.html). Looping through and matching values like in the
above example (code rewriten in javascript).
BUT here ends my success. The AJAX code is identical to the one in the above supplied example (except of course the reference to getData.html), and everything else seems to be working so I won't bother you with my entire code. In the example mentioned, at the very buttom of the PHP-file it says
//output the response
echo $response;
This is where javascript seems to be failing. I've desperately been trying to echo / print the response but for some reason, it doesn't get returned to index.php properly. The only way to force it to display at least something is to either use php echo, or simply just write plain html text somewhere in the getData document within the HTML tags. I've also tried getElementById('txtHint').innerHTML = "hello"; to see if it works but with no success.
The most obvious way to do this would be to simply replace echo $response with the equivalent in js:
document.write(response);
but whatever document.write prints, nothing's dipslayed. The div in which the "hint" is supposed to pop up is yet empty. I've googled solutions, different ways of printing js variables with no further success. Perhaps, document.write is not "compatible" with XML or AJAX responseText? There must be a simple solution to this. Hope you guys can help me out. Thanks!
php is of course a server-side language that emits a page and runs on your back end.
js is of course a client-side language that runs on the user's front end.
document.write() is the proper function for emitting client-side text; it runs at page load time. Example:
<b>My domain is: <script>document.write(document.domain);</script></b>
properly gives
My domain is: www.mydomain.com

Javascript closures and execution contexts - problems with evalled code

I think I have a problem with closures and execution contexts, although I'm not really sure.
Let me explain exactly what I'm trying to do and why I've coded it in the way I have:
1) I'm building a javascript powered interface, the interface contains different apps (I'm calling them widgets).
2) All the widgets are moveable/dragable/closeable/resizeable etc.. I'm trying to achieve something like a desktop interface although has to be said that what I've got is far less than a web based opperating system. But that is what I'm aiming for.
3) So I needed a way for the JS code to load each of these widgets without knowing which widgets exist and/or anything else about them. I decided that when the interface is loading it should call a php script to find out the names of the widgets.
4) The JS code has the name of each widget, it now loops through them all calling another php script, this php script will feed back the code for loading that particular widget and the html code to display it. The JS appends elements to the screen for the display and then it loads the JS code for the widget.
5) This is the tricky part, actually loading the code for each widget, I did it like this:
var func=new Function(ajax.responseText);
func();
And it works fine, or appears to atleast.
6) Now I have a problem with objects and arrays and I think it has something to do with execution contexts.
Array Example:
var myArray=new Array('foo', 'bar', 'fooBar', 'barFoo');
Looks OK to me, no problem with the actual array (unless I typed something wrong in there :) can't work without my Net Beans editor) I tried running this as a seperate script and it works fine, ie; with: alert(myArray[0]); resulting in foo
Array Problem:
My JS code can't do anything usefull with this array because actually calling alert(myArray[0]); will result in foo, bar, fooBar, barFoo.. No idea why this happens really but it's really messing everything up now.
Object Example:
var myObject=new Object();
myObject.a='foo';
myObject.b='bar';
myObject.c='fooBar';
myObject.d='barFoo';
Again, object works fine when run by it's self.
Object Problem:
Very similar problem as with arrays, calling alert(myObject['a']); will actually result in [object Object],[object Object],[object Object], [object Object] ...
...so that's the same problem as with arrays, but it gets even worse with objects, if I call alert(myObject.a); (notice that i didn't use ['a'] this time) it will just result in undefined.
So to backtrack a little and further explain the way that everything is tied in together:
1) when the JS loads it will call a php script which returns a JSON encoded object containing 3 keys('functions', 'JSscript', 'Other'). Each key contains the source code of another javacript file. These are all loaded using a dynamically created function like: var func=new Function(ajax.responseText).
2) Then it's these new javascript codes that call another php script for further directions.
3) Php responds with JSON, which is evaluated inside a dynamically created function and stored in a new variable.
4) The new variable is now an object containing maybe 3 keys (html, javascript, anotherObject) The html is appended into the document, The javscript is executed in a new function as above.
5) The problems come with objects/arrays that exist in the JS executed in my last statement.
So if anyone can help me out on this I'd be greatfull, and if you need further explaination or code examples then obviously I'll be happy to provide.
Thanks,
Richard
Could it be that you're not parsing your ajax response text.
Ohhhh.. Turns out this was nothing to do with closures or any other javascript for that matter, sorry to excite you all.
It was caused by a php script, and not even the php script that handles ajax requests, it was actually the script that reads the javascript files and then JSONs them. That script also has a find and replace function like a simple templating system where it will find all the words between '[' & ']' which unfortunately means any arrays in the javascript will get bungled up.
I used the find and replace with square braces because it was originally meant for html templating, I just didn't consider it properly when I started using the system in my JS code aswell.
So to clarify, my php script would change JS of obj[var].description into obj.description which is valid JS so didn't flag any errors for me to notice it.
Ohhhhh. What a loser :)

HTML Encoded strings recognized by the javascript engine, how's it possible?

Well. This night was a very strange night to me. I am sorry to create a new question after creating two other questions previously, but this is another argument at all. If I get an answer here, I'll get an answer to those questions too so please somebody listen to me and try to understand.
It all began with a simple script JS to be generated through an aspx codebehind file.
On a control, I had to put a JavaScript in this way:
this.MyTxtBox.Attributes["onfocus"] = "windows.alert('Hello World!');";
OK. You might think, where's the problem? The problem is that ASP.NET 4.0 encodes everything, and I say everything in order to avoid XSS to be performed on a site. Well this might not seem a problem but if you look at the rendered page you'll make a jump on the chair like I did:
<textarea id="..." onfocus="windows.alert('Hello World!');"></textarea>
As you can see the html, the final html is a bit odd... JavaScript engine should not accept this situation.
So I started this questions:
ASP.NET quote character encoding causes problems when setting a control's property
Asp.Net encoding configuration
Well I still haven't got any answer YES we could not understand what the hell it is necessary to modify in the .net configuration in order not to let this situation happen.
But now I consider one thing, one important thing: JavaScript engine works!
Even with that odd code that should not be interpreted...
I hope everything was clear until now... The question now comes:
Is this a normal situation for the JavaScript engine?
Does every browser will correctly interpret a JavaScript having quotes replaced with their encoded strings?
If this is true I have to suppose that the .net does not provide a mechanism to avoid encoding just for this reason!
Re:
<textarea id="..." onfocus="windows.alert('Hello World!');"></textarea>
There's nothing odd about that (other than your using windows.alert instead of window.alert). It should work fine (and does; example). The HTML parser parses HTML attribute values, and handles processing entities like '. The JavaScript source code it eventually hands to the JavaScript interpreter will have quotes in it. The browser doesn't hand the literal characters & # 3 9 ; to the JavaScript interpreter.
It's just the same as:
<input type='text' value="This is a 'funny' value too">
The HTML parser processes the entities, and the actual value assigned to the input is This is a "funny" value too.
Incidentally, this is also why this seemingly-innocent HTML is actually wrong and will fail validation (although most browsers will allow it):
<a href='http://www.google.com/search?q=foo&hl=en'>Search for foo</a>
More correctly, that should be:
<a href='http://www.google.com/search?q=foo&hl=en'>Search for foo</a>
<!-- ^^^^^--- difference here -->
...because the HTML parser parses the value, then assigns the parsed result to the href attribute. And of course, an & introduces a character entity and so to literally get an & you must use & everywhere in HTML. (Again, most browsers will let you get away with it if what follows the & doesn't look like an entity. But that can and will bite you.)

Categories