I'm a noob in Javascript but here is my problem:
I'm cleaning up some PHP-files. Some of them contain Javascript functions which I want to transfer to a separate xxx.js file.
Most of them are working fine again but one causes me trouble. I think because of the punctuation (the ' and ").
Here's the script as it shows up IN the PHP-file:
function preview(){
dd=window.open('','prv','height=600,width=500,resizable=1,scrollbars=1')
document.addnews.mod.value='preview';document.addnews.target='prv'
document.addnews.submit();dd.focus()
setTimeout(\"document.addnews.mod.value='addnews';document.addnews.target='_self'\",500)
}
When copying this to the xxx.js file it won't work.
Anybody knows how it should look in a real .js-file?
Thanks in advance!
Cleaned a bit:
function preview() {
var dd = window.open('', 'prv', 'height=600,width=500,resizable=1,scrollbars=1');
document.addnews.mod.value = 'preview';
document.addnews.target='prv';
document.addnews.submit();
dd.focus();
setTimeout(function() {
document.addnews.mod.value = 'addnews';
document.addnews.target = '_self';
}, 500);
}
Remove the backslashes in front of the double quotes.
setTimeout("document.addnews.mod.value='addnews';document.addnews.target='_self'",500)
It looks like this function was originally in a double-quoted string, so all double-quotes inside are escaped. Good for you for moving them out of PHP :)
Related
I have a c# function that builds a string which in turn is used as a hyperlink to another page. However, with some strings with single quotes it is causing a javascript error as shown here:
I'm calling the javascript function in the code behind as so
linkFullMatch.NavigateUrl = "javascript:showFullMatches(" + sb.ToString() + ")";
the javascript is on the aspx function as so:
<script>
function showFullMatches(url) {
window.open(url, "_blank", "height=344,width=1100,scrollbars=yes,resizable=yes,toolbar=no,location=no,status=no,menubar=no,left=580,top=194");
}
Any help would be greatly appreciated. Any string that doesn't have a single quote in works fine and the page link opens as requested.
Rob
You need to add an additional layer of quote marks to make the sb.ToString() value an JS string. Adjust your call like:
linkFullMatch.NavigateUrl = "javascript:showFullMatches('" + sb.ToString() + "')";
Note the additional ' marks.
I have the following javascript code that attempts to insert HTML code dynamically. I have an error the syntax but I do not know how to correct it. Please can someone advise?
loadNextContainer.innerHTML = '<span class="sr_43" id="srloadnext_2" onclick="srt.loadNextMatchRecords(\''+numDownloadSoFar+'\', \''+maxDownloadLimit+'\', \''+folderName+'\', \''+jsonHashTags+'\', \''+fromDate+'\', \''+toDate+'\', \''+lastScanId+'\')">LoadNext</span>';
ERROR MESSAGE:
Uncaught SyntaxError: Invalid or unexpected token
I believe the error revovles around the function variables. In particular the JSON variable. I cannot change the use of double quotation marks for each element in the JSON. So that has to stay in any solution.
You could try it using backticks like this.
loadNextContainer.innerHTML = `<span class="sr_43" id="srloadnext_2" onclick="srt.loadNextMatchRecords('`+numDownloadSoFar+`', '`+maxDownloadLimit+`', '`+folderName+`', '`+jsonHashTags+`', '`+fromDate+`', '`+toDate+`', '`+lastScanId+`')">LoadNext</span>';
Or just escape the double-quotes instead of the single quotes. The way you're doing it, you're unintentionally opening up the string when you try to escape it.
loadNextContainer.innerHTML = "<span class=\"sr_43\" id=\"srloadnext_2\" onclick=\"srt.loadNextMatchRecords('"+numDownloadSoFar+"', '"+maxDownloadLimit+"', '"+folderName+"', '"+jsonHashTags+"', '"+fromDate+"', '"+toDate+"', '"+lastScanId+"')\">LoadNext</span>";
Judging from your image of your variables, none of the template literal solutions are going to help you, because at least one of your parameters is an array.
Yes, it would be possible, with enough effort, to convert that array into a string representation that would work with innerHTML. But it's going to be very difficult. You'd end up needing to use JSON.stringify to get the string version of your array at least.
An easier solution is actually going to be to create the element and then add the onclick operator through pure javascript, like this:
var s = document.createElement('span');
s.className = 'sr_43';
s.id = 'srloadnext_2';
s.innerText = 'LoadNext';
loadNextContainer.appendChild(s);
s.onclick = function(e) {
srt.loadNextMatchRecords(numDownloadSoFar, maxDownloadLimit, folderName, jsonHashTags, fromDate, toDate, lastScanId);
};
Try it with template literals:
loadNextContainer.innerHTML = `<span class="sr_43" id="srloadnext_2" onclick="srt.loadNextMatchRecords(\'${numDownloadSoFar}\', \'${maxDownloadLimit}\', \'${folderName}\', \'${jsonHashTags}\', \'${fromDate}\', \'${toDate}\', \'${lastScanId}\')">LoadNext</span>`;
Edit:
As others already mentioned. Sorry.
I've added to my HTML these lines:
"</script>$(document).ready(func a() {
$('img').click(function(){
return $(this).attr('src');
});
});</script>"
and if I set instead of return - alert, then I get what I need.
Later I've tried this on my tap recognizer function:
var a = self.webView.stringByEvaluatingJavaScriptFromString("a()")
print(a)
but it prints me an empty string. What I do wrong? Can anyone help me to fix that?
I may be a little late but AFAIK you should call "a();". You might be missing the semicolon
I want to escape javascript entities on client side. For example :-
If my input string is tes"t result should be tes\"t
Is there any inbuilt function provided by jquery for this ?
This is a really crazy, almost stupid shot in the dark on my part, but...
If you're using a server-side language like PHP to output variables' contents into JavaScript, you should use json_encode as this handles ALL escaping for you, regardless of the type of variable.
On the other hand, if you're (I really hope you're not) doing something like this:
var input = "test"t";
And trying to escape that properly while in JavaScript... that's not going to work. It's a syntax error. You need to escape your literals manually.
Kevin van Zonneveld provide a JavaScript equivalent of PHP’s addslashes here :
http://phpjs.org/functions/addslashes/
function addslashes(str) {
// example 1: addslashes("kevin's birthday");
// returns 1: "kevin\\'s birthday"
return (str + '')
.replace(/[\\"']/g, '\\$&')
.replace(/\u0000/g, '\\0');
}
Based on this function, I guess you might want to add this function to prototype of the String like this.
if (!String.prototype.addslashes) {
String.prototype.addslashes = function () {
return this.replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
};
}
var str = 'tes"t';
alert(str.addslashes()); // shows 'tes\"t'
DEMO: http://jsfiddle.net/naokiota/6F6aN/6/
Hope this helps.
I have a JS function which is generated by some PHP, the function call is below:
onClick=openPopup('".$row['imgname']."','".$row['adtitle']."','".$row['adviews']."')
Now this works unless the value of $row['adtitle'] contains a JS keyword. The one that brought the bug in my code to my attention was the word 'THIS'. Would there be a way to escape these values, I can't figure it out as I have already used a lot of encapsulation in this call.
Thanks in advance.
EDIT:
openPopup('efc86f7223790e91f423ef1b73278435.jpg','THIS IS A TEST ADVERT 12345678','2')
This call does not work.
openPopup('eada91a6c1197d2f2320e59f45d8ca6b.jpg','is a test','2')
however this one does work..
only thing I could figure was the THIS as when looking at the source, the text following THIS is highlighed differently.
Edit 2 : Here is my function:
function openPopup(imgname,adtitle,adviews) {
document.getElementById('popup').style.display = 'block';
document.getElementById('delimg').src = 'imgstore/' + imgname;
document.getElementById('delAdTitle').innerHTML = adtitle;
document.getElementById('delAdViews').innerHTML = adviews;
document.getElementById('confirm').onclick = function() {
location.href = '?delete=1&id=' + imgname;
}
}
Maybe it’s just a question of proper formatting:
$onclick = 'openPopup('.json_encode($row['imgname']).','.json_encode($row['adtitle']).','.json_encode($row['adviews']).')';
echo 'onClick="'.htmlspecialchars($onclick).'"';
Note that we’re abusing json_encode here to quote the JavaScript string literals. Although we shouldn’t as strictly speaking JSON strings are not a subset of JavaScript strings.