How to view and handle hidden data in variables in javascript - javascript

How do I view and extract data inside a variable, populated from another piece of code, that may contain hidden escape characters or data in Javascript (JQuery stuff is fine too)?
For example lets say I have an Ajax call such as this, where data is printed from a back-end script written in Lua:
success: function(data)
{
dataItems = data.split(",");
}
Lets say I'm expecting a four letter string in each of the dataItems array. If I use Chrome or Firefox putting a breakpoint on dataItems I see each array containing a four letter string and I'm happy because it looks right and I can now process it. However if I do a print(dataItems[1].length) for example I notice it has a length of 5, and my debugger shows dataItems[1]="abcd", obviously there is something hidden inside it that doesn't show easily as part of the arrays variable. Is there a better way to catch and view these hidden pieces of information preferably in a browser debugger? How does one go about removing this undesired data once it is recognized.

I think it's surrounded with empty spaces.
Try:
console.log(dataItems[1].trim().length);

Related

How to hide or encrypt a query string variable

How can i make the variable 'success' that is passed to 'payment_success.php' below to be somehow encrypted, i don't want the user to know the exact variable name passed. i wanted using post method, but i can't use it for my call back function. Any idea will be a great help
callback: function(response){
const referenced = response.reference;
window.location.href='payment_success.php?success='+referenced;
},
The following is one of tricks I used in a project trying to hide a piece of data.
Assuming your string variable is "123abc".
You may first add a random suffix of three characters , so the string can be:
AC1 C8D E9u Z77 Vux
After that you may use a further trick to put your code "123abc" into a format like the following
1[3 random characters]2[4 random characters]3a[2 random characters]bc[3 random characters]
So the result of 123abc will be like
XXX1XXX2XXXX3aXXbcXXX
so can be any one of the following:
56f134a2rxxq3a43bcccd
97z1zux289873a5tbczwq
Eu11qzv2739u3auubc76x
and so on....
After passing to your PHP script, please extract the correct data.
If you want to be safer, split the characters more further apart by inserting longer random characters in between.
You may use further imagination to do the trick. For example, generate a string which can be random in length of the "mixing codes".

What is the right way to pass data from PHP application to JS?

Let's say i want to open a PHP page and without another request, pass some JSON data directly to the browser, so it will be accessible to my Javascript functions.
I don't know the right way to do it, but what i do currently is something like this :
<textarea id="mydata" style:"display:none">[{code:1,name:'John'},{code:2,name:'Mary'},{code:3,name:'Paul'}]</textarea>
I put the data inside a invisible textarea and now the data inside 'mydata' textarea is accessible by JS doing something like this :
var myData = JSON.parse($('#mydata').val());
Although this works, somehow it does not seem to me the right way to do it... I know i could avoid to 'dirty' the html code by getting the data using Ajax after the page opens, but what i'm trying to do here is avoid more requests, so with only one request, everything will be accessible. Actually in my application i have about 5 textareas like these, so with only 1 request to the server i get all data needed.
Thanks
From PHP's perspective, there is no difference between this:
<textarea id="mydata" style:"display:none">[{code:1,name:'John'},{code:2,name:'Mary'},{code:3,name:'Paul'}]</textarea>
and this:
var myData = [{code:1,name:'John'},{code:2,name:'Mary'},{code:3,name:'Paul'}];
Both of the above take the form of:
[a string][the serialized object][a string]
Whether you're surrounding the values with HTML or with JavaScript, that surrounding decoration is just raw output strings as far as PHP is concerned. So there's no need to add the extra step of outputting the JSON to a form element and then using JavaScript to get the form element's value as a string and parse it back to an object. You can just emit the object itself directly to JavaScript code.

How can I get Javascript to execute as a table is being built?

I have a table being built in HTML (using ASP), and it's stepping through a recordset. As it steps through the recordset, it creates a new row for the html table and fills it with data.
The problem I'm having is that it's using numbers that can be 10 or 11 digits long, and I want to format it with commas. I have a formatNumbers function that works excellently. However, basically what I need to do is this:
<td><script>formatNumber(<% = RS("total_rolled_lineal_ft")%>,0,0,true);</script></td>
I'm getting an Object Expected error. If we take a line from the executed HTML, here's what it looks like:
<td><script>formatNumber(10843537,0,0,true);</script></td>
Any clue what's causing my error, or, if I'm doing it completely wrong, how to fix it?
Also, formatNumber returns a string, in this case 10,843,537.
Thanks to #nnnnnn, I ended up using VB's FormatNumber() and came up with this
<% = FormatNumber(RS("total_rolled_lineal_ft"),0,true,true,true)%>, which works excellently.
I have never used straight ASP so maybe I am missing something in this answer.
Technically you can not execute Javascript while the ui is rendering, browsers tend to be a single threaded affair and will do one thing or the other.
But I would suggest that instead of binding the table directly to a record set you transform the record set into a ViewModel type class in the code behind.
You would then perform this conversion as you are building your ViewModel.

Javascript parse innerhtml

I have a HTML page full of data separated by commas and each row ends in a (br /) tag. In Javascript I can get this from the DOM by asking for the innerHTML of the element containing the data.
My question is how to parse the innerHTML to get the data out from between the commas and start on the next line when it hits the (br /) tag?
You can probably ignore the rest as that is my question above.
When I parse each line I will start a new object and put the data into it. I'm just not sure what to do with the innerHTML!
I did put the data through a CSVtoarray function I found but ended up with an array of one large array instead of an array of arrays for each line. I can work my way through this array creating objects from the data along the way but turning the innerHTML into a single array seems an unnecessary step when I could parse the data straight into object.
The data is put there via AJAX. I can change the format that the data comes in. As I said I have it separating data with commas and (br /) tag at the end of the line. I do not know if this is stupid or not.
So, you want to csv-parse a file where newlines are indicated with <br /> instead of \n? Just use that separator in your CSV-Parser then. Simple version:
text.split("<br />".map(function(line){ return line.split(","); })
You could also split by regular expressions, like
text.split(/\s*<br ?\/>\s*/)...
If you really habe the CSV data in a DOM, you could remove all the br-element and use the remaining (text) nodes as the lines-array.
You mention that you have control over the data you're getting via AJAX, and you're right that your current approach is not the best idea. First off, you should never try to parse HTML on your own, even if you think it's "simple" – different browsers will give you different innerHTML for the exact same content. Instead, use the DOM to find the information you're looking for.
That said, the correct approach here is just to return a JSON object from the server; you'll then have direct access to your data. Nearly every server-side language has some kind of facility to output JSON, and JavaScript can parse the JSON string natively1 with JSON.parse().
From the server, return:
{items: [
{ id: 0, name: '...' },
{ id: 1, name: '...' },
...
]}
On the client (assuming jQuery),
$.getJSON('/path-to-script/', function(d) {
for (var i = 0; i < d.items.length; i++) {
d.items[i].id;
}
});
1 - in modern browsers
You could simply do this if you just want to "get the data out from between the commas":
yourElem.innerHTML = yourElem.innerHTML.split(",").join("");
Or if you just want an array of lines:
var lines = yourElem.innerHTML.split(",");
That'll return an array of lines with <br> elements intact. It's not clear if that's what you want, though.

Need help with an AJAX workflow

Sorry I couldn't be more descriptive with the title, I will elaborate fully below:
I have a web application that I want to implement some AJAX functionality into. Currently, it is running ASP.NET 3.5 with VB.NET codebehind. My current "problem" is I want to dynamically be able to populate a DIV when a user clicks an item on a list. The list item currently contains a HttpUtility.UrlEncode() (ASP.NET) string of the content that should appear in the DIV.
Example:
<li onclick="setFAQ('The+maximum+number+of+digits+a+patient+account+number+can+contain+is+ten+(10).');">
What is the maximum number of digits a patient account number can contain?</li>
I can decode the string partially with the JavaScript function unescape() but it does not fully decode the string. I would much rather pass the JavaScript function the faq ID then somehow pull the information from the database where it originates.
I am 99% sure it is impossible to call an ASP function from within a JavaScript function, so I am kind of stumped. I am kind of new to AJAX/ASP.NET so this is a learning experience for me.
First of all, if you're pulling the questions from the db on page load you most likely have all the answers too, so just keep going with your current approach by jamming the answers into the page as your code sample is doing. Unless your FAQ list has thousands and thousands of questions, doing it the "AJAX way" by hitting the db on each click of the list item doesn't give you much here IMO. If it does have that many questions then a straight list is the wrong way to go anyway.
Secondly, two things to keep in mind re your approach:
you're placing html inside an html attribute
the attribute is specifying a javascript function to call
So you need to make sure your "answer" escapes both html and is valid js. By valid js I mean it can't have new lines and must escape quotes properly. For example, the following html - although valid html - won't fire the onclick and you'd just get a js syntax error:
<li onclick="setFAQ('This line's
multi line and has a single quote in it!')"
To account for these I would say HttpUtility.HtmlAttributeEncode in tandem with System.Web.Script.Serialization.JavaScriptSerializer is more appropriate to the markup you've shown.
JavaScriptSerializer json = new JavaScriptSerializer();
string answerString = "This line's\nmulti line and has a single quote in it!";
string onClickJS = String.Format("setFAQ({0})", json.Serialize(answerString));
string onClickAttr = HttpUtility.HtmlAttributeEncode(onClickJs);
Even better, use .NET's ListItem object and lose HtmlAttributeEncode altogether:
ListItem faqItem = new ListItem(questionString);
faqItem.Attributes.Add("onclick", String.Format("setFAQ({0})", json.Serialize(answerString)));
The html portion is escaped automatically for you, plus it's a lot cleaner.
As for your javascript, you don't have to decode anything in setFAQ(). Just take its argument and put it in into you "answer" div:
function setFAQ(answer) {
document.getElementById('answer').innerHTML = answer
}
I think just using HttpUtility.HtmlEncode may solve your problem. I'm not sure I follow completely though : \

Categories