Unexpected Number error - javascript

I have been writing a function to allow users to upload images from their local file system to a website using JavaScript. I have successfully been able to upload images to the browser.
I have also written a function to allow the user to delete these images.
var count = 0;
function getPhoto(){
var file = document.getElementById('ad_photo');
var list = document.getElementById('ad_photo_upload');
var fReader = new FileReader();
var photo_list = [];
var counter;
fReader.readAsDataURL(file.files[0]);
fReader.onloadend = function(event){
counter = count.toString();
list.innerHTML += "<li id = 'pic " + counter + "'><img src='" + event.target.result + "'></img><a class = 'close' onclick = 'rem_pic(pic " + counter + ")'>X</a></li>";
photo_list[count] = event.target.result;
count++;
}
}
function rem_pic(theID){
var element = document.getElementById(theID);
element.outerHTML = "";
delete element;
}
My issue is whenever I call the "rem_pic(theID)" function I get a Chrome Browser error message that says "Uncaught SyntaxError: Unexpected number". Does anyone have any clue to why this might be? And how I could possibly improve the functions I have written so they work correctly?
Thanks

This happens because you pass a number to your function:
'rem_pic(pic " + counter + ")'
will render to
'rem_pic(pic 1)'
^ or any other number according to your counter value
And this is wrong as javascript params can't contain spaces.
So you probably need to pass a string:
rem_pic(\"pic " + counter + "\")
Looking at your code seems like you use it's as HTML id attribute. id attribute can't contain space chars too so your code should be like
rem_pic(\"pic" + counter + "\")
if your id in layout has format id="pic1", id="pic2", etc.

Related

What causes these JS scripts to prepend undefined to values in first tsv output column?

I've created a number of JS scripts similar to below which generate a .tsv download of the webscraped data (this particular example assumes you're on the URL of a repo's Contributors page on Gitlab). Everything outputs fine when I open the .tsv in Microsoft Excel, except that the string 'undefined' appears prepended to every value after the header row in the first column only
How do I edit the script to omit undefined from appearing? Even if it's a simple fix, it will allow me to clean up a bunch of scripts' similar output scraping other websites.
javascript:(function(){
var arr = new Array, i, commitsemail, commitsnum, email, fullname, matchnum;
var regexnum = /.+?(?=commits)/g; var regexemail = /(?<=\().*(?=\))/g;
var glab = document.querySelectorAll('div.col-lg-6.col-12.gl-my-5');
var strings='Full name'+'\t'+'Email'+'\t'+'# of commits'+'\r\n';
var endurl = document.URL.split(/[/]+/).pop(); if (endurl != 'master') {
alert('You are not on the contributors page of a Gitlab repo. Press Esc key, go to URL ending with /master and re-run this bookmarklet'); } else {
for (i = 0; i<glab.length; i++) {
fullname = glab[i].getElementsByTagName('h4')[0].textContent;
commitsemail = glab[i].getElementsByTagName('p')[0].textContent;
commitsnum = [...commitsemail.match(regexnum)];
email = [...commitsemail.match(regexemail)];
arr[i] += fullname + '\t' + email + '\t' + commitsnum;
strings += arr[i]+'\r\n'; }
var pom = document.createElement('a');
var csvContent = strings; var blob = new Blob([csvContent],{type: 'text/tsv;charset=utf-8;'});
var url = URL.createObjectURL(blob); pom.href = url; pom.setAttribute('download','gitlab-contributors.tsv'); pom.click(); }
})();
It's because of the += on the line with arr[i] += fullname + '\t' + email + '\t' + commitsnum;. Change that to an = instead.
Before the assignment, arr[i] is undefined. Maybe you mixed up the syntax for assigning an array entry by index, with appending to an array (arr.push(...)), thinking += would push, but it doesn't. It appends the new value to the current value. And since that line is the first time arr[i] is assigned anything, the current value is undefined.

jsSHA512 different hashes from same string

I'm using the jsSHA library to hash passwords but I'm getting different hashes, from the same string, everytime I run the script:
/* Password hash function */
var b = $("form#register"),
shaObj = new jsSHA('SHA-512', 'TEXT');
b.on('submit', function (e) {
e.preventDefault();
var p = $('#reg_pwd'),
q = $('#confirm_pwd');
shaObj.update(p.val());
var p_hash = shaObj.getHash("HEX");
//p.val(p_hash);
shaObj.update(q.val());
var q_hash = shaObj.getHash("HEX");
//q.val(q_hash);
$('p').html('String: ' + p.val() + '<br />Hash: ' + p_hash +
'<br />String: ' + q.val() + '<br />Hash: ' + q_hash)
//this.submit()
});
I've been able to reproduce this in a fiddle. Just type any text in one of the fields and press submit many times to see the hash changing. It's working fine in the demo page, though.
What is going on?
jsSHA's .update() method appends additional data after any previous updates, effectively concatenating them together:
shaObj.update(p.val());
shaObj.update(q.val());
// similar to...
shaObj.update(p.val() + q.val());
To calculate hashes for each input, you'll have to create a new jsSHA() instance for each:
var shaObj = new jsSHA('SHA-512', 'TEXT'); // <---
shaObj.update(p.val());
var p_hash = shaObj.getHash("HEX");
//p.val(p_hash);
var shaObj = new jsSHA('SHA-512', 'TEXT'); // <---
shaObj.update(q.val());
var q_hash = shaObj.getHash("HEX");
//q.val(q_hash);

Define session variable in c# get it from javascript

I'm saving string that represents the URL in a session variable from my code behind like this:
String mois = Request.QueryString["mois"].ToString();
String m = mois;
String moisnom = Request.QueryString["moisnom"].ToString();
String annee = Request.QueryString["annee"].ToString();
String dt = Request.QueryString["date"].ToString();
String user = Request.QueryString["user"].ToString();
String where = "jour.aspx?mois=" + mois + "&moisnom=" + moisnom + "&annee=" + annee + "&date=" + dt + "&user=" + user + "&cp=all" + "&usl=" + Request.QueryString["usl"].ToString();
Session["togo"] = where;
And then I try to get it like this in JavaScript like this:
var togo = '<%=Session["togo"]%>';
// i also tried this var togo ='#Session["togo"]';
var newPage = togo; // this should contain a string with the url to go to
But when I use it it uses it as a string here is what my URL looks like:
http://localhost:50311/<%=Session["togo"]%>
or
http://localhost:50311/#Session["togo"]
How else can I access the session variable or what am I doing wrong please?
EDIT:
like you suggested i already tried using the hidden field like this
yes i tried that but then i had this problem here is the definition of the hidden field
<input type="hidden" value="aa" id="myHiddenVar" runat="server"/>
then i tried giving it the value i need on click
String where = "jour.aspx?mois=" + mois + "&moisnom=" + moisnom + "&annee=" + annee + "&date=" + dt + "&user=" + user + "&cp=all" + "&usl=" + Request.QueryString["usl"].ToString();
myHiddenVar.Value= where;
and this is how i tried getting it from the js file
var togo = $('#myHiddenVar').val();
var newPage = togo;
but it takes the default value meaning "aa" as in value="aa" i gues cause the script is executed before the assignment of the variable any way how to reverse that order ?
After Session["togo"] = where;
save this Session["togo"] in hidden variable
hiddenVariable= Session["togo"];
Now in JS access that hiddenvariable:
suppose ID of hiddenvariable is "hdnxyz"
var togo = $('#hdnxyz').val();
var newPage = togo;
first of all session resides on server!!!!!!
If it is in different js file than you cant access it <%xyz%> i.e scriplet tags only work on aspx page...
so there is no way to access the session variable on client side..
instead assign your sessio9n value to a hidden variable and then access it using javascript
Write Session element in a asp:HiddenField and then read from it with your js code.

Extract string html with regex on interval

There is a public website with this in the source:
</div><script type="text/rocketscript">
function calculateIndexIncome() {
var khs = $('#t9').val();
var btcusd = $('#t9_1').val();
var btckhs = $('#t9_2').val();
var dayprofitperkhs = 0.00000018188885404454654
var arr = btcusd.split(' ');
btcusd = arr[0];
var totalinvestmentusd = ((khs * btckhs) * btcusd).toFixed(2);
var totalinvestmentbtc = (khs * btckhs).toFixed(8);
var dailyincomebtc = (khs * dayprofitperkhs).toFixed(8);
var dailyincomeusd = ((khs * dayprofitperkhs) * btcusd).toFixed(2);
var monthlyincomebtc = (dailyincomebtc * 31).toFixed(8);
var monthlyincomeusd = (dailyincomeusd * 31).toFixed(2);
var breakevendays = (totalinvestmentusd / dailyincomeusd).toFixed(0);
var monthlypercentage = ((100 / breakevendays) * 30).toFixed(2);
$('#tl').html('Total KHS: ' + khs + '<br/>Total Investment: ' + totalinvestmentbtc + ' BTC ($' + totalinvestmentusd + ' USD)<br/><br/>Daily Income: ' + dailyincomebtc + ' BTC ($' + dailyincomeusd + ' USD)<br/>Monthly Income: ' + monthlyincomebtc + ' BTC ($' + monthlyincomeusd + ' USD)<br/><br/>Break Even In: ' + breakevendays + ' Days.<br/><br/>Monthly Rate: ' + monthlypercentage + '%');
}
I need to be able to extract two values: btckhs and dayprofitperkhs.
if I look at page source, dayprofitperkhs is different everytime I refresh.
Edit:
Jimmy Chandra came up with this bookmarklet:
javascript:
setInterval(logging,60000);
w1 = window.open("https://scrypt.cc/index.php");
function logging(){
console.log (w1.$('#t9_2').val());
var re=/var\s*dayprofitperkhs\s*=\s*([0-9\.]+)\s*/gi;
var matches=re.exec(document.body.innerHTML);
console.log(RegExp.$1);
w1.location.href = 'https://scrypt.cc/index.php';
}
This works ALMOST perfectly. it gets the dayprofitperkhs, but only on the first interval.
After that, the value is no longer updated, although t9_2 IS updated...
Anyone?
I don't know where that site is, so I am just running this against this SO question, but the following bookmarklet is getting me what I want...
As I mentioned in the comment, I use Regular Expression against the document body inner html and I am looking for dayprofitperkhs and capturing the numbers and decimal separator on the right side of the equal sign. Also trying to compensate for any extra spaces in between (\s*). RegExp.$1 gave me the number that I am looking for.
javascript:(function(){var re=/var\s*dayprofitperkhs\s*=\s*([0-9\.]+)\s*/gi;var matches=re.exec(document.body.innerHTML);console.log(RegExp.$1);}());
So your final bookmarklet should be something like:
javascript:
setInterval(logging,60000);
w1 = window.open("siteurl.com");
function logging(){
console.log (w1.$('#t9_2').val());
var re=/var\s*dayprofitperkhs\s*=\s*([0-9\.]+)\s*/gi;
var matches=re.exec(w1.document.body.innerHTML);
console.log(RegExp.$1);
w1.location.href = 'siteurl.com';
}
The variables in question are local variables within the calculateIndexIncome() function, so no, you can't access them from outside that function.
The reason the first one "works" is because you're not referring to the variable, but rather the value: $('#t9_2').val(). This is a jquery selector which finds the element with the ID t9_2 and grabs its value.
You cannot visit it because its a local variable, it only exists in calculateIndexIncome() function.
By the way, you needn't open a new window to visit the variables. You can use chrome dev tools to directly modify the javascript to print the values, or set a breakpoint to debug the code.
Here is a tutorial for chrome dev tools: https://www.codeschool.com/courses/discover-devtools

ExtJS/JavaScript - show image when using replace() function

I'm not sure exactly how much this question has something to do with ExtJS and how much with pure JavaScript. Anyways I have a string with comma separated value. I need to use for the GUI so I try to make it as user-friendly as I can. I made most of the things I wanted but one thing I can't accomplish yet. I want to replace all commas in the string with a proper image, which I think will fit very well on what I'm doing but for now - I try with no success.
For those familiar with ExtJS - I'm doing this for each cell in a certain column of a grid with a render function. But I think that maybe the problem must be solved with a pure JavaScript function. Here is what I have by now:
_cusomizeString: function(dates) {
if (dates != null)
{
var date = dates.replace(/,/g,"|");
var www = date.split('|');
var xxx = www.length;
for (var i = 2; i < xxx; i+=3)
{
www[i] = www[i] + '<br />';
}
var ggg = www.toString();
var hhh = ggg.replace(/,/g,'<img src =" ' + D:\dir1\dir2\dir3\dir4\dir5\img.png + ' "/>');
return hhh;
}
return dates;
}
I tried a few variations, now I don't get error but don't see an image either.
Thanks
Leron
P.S
With this change in the function:
var finalString = tempString.replace(/,/g,'<img src ="http://www.finishingtouch.co.uk/assets/images/common/calendar_icon.png"/>');
I am able to visualize this:
The main problem now is how to add the image before the first element, because now it's missing (Noticeable especially when there's only one date) and how I can make it work with local files for now? I've tried using this in my replace function:
'<img src ="file:///D:\\symapac\\src\\public\\img\\icons\\draft.png"/>'
But the console log returns this and I dont see no image:
07-06-2012<img src ="file:///D:\dir1\dir2\dir3\dir4\dir5\img.png"/>16-06-2012
Ok, I have almost final solution. Here is how it looks like:
Here is my final function:
_checkDates: function(dates) {
if (dates != null)
{
var date = dates.replace(/,/g,"|");
var arrayOfDates = date.split('|');
var stringLength = arrayOfDates.length;
for (var i = 2; i < stringLength; i+=3)
{
arrayOfDates[i] = arrayOfDates[i] + '<br />';
}
var tempString = arrayOfDates.toString();
var finalString = tempString.replace(/,/g," ,");
finalString = finalString.replace(/,/g,"<img src="+ "'" + pathToImage + "'" +"/>");
var imgSrc = "<img src="+ "'" + pathToImage + "'" +"/>";
var otuputString = imgSrc.concat(finalString);
return otuputString;
}
return dates;
}
There is that little problem that no matter now many tabs I put in var finalString = tempString.replace(/,/g," ,"); the space between the icons is always the same, no idea why. But that's the closest I get to what I've wanted.
Cheers
Leron
'<img src ="file:///D:/dir1/dir2/dir3/dir4/dir5/img.png"/>'
You have a space before your filename, also your filename isn't in quotes.

Categories