var url = "C:\xampp\htdocs\wcf2\wcf/attachments/5d/18-5dffacdfe6d2cf1db8dfabbb5b53ae8dc65bd325";
results in Uncaught SyntaxError: Unexpected token ILLEGAL. Is there any way to fix it in javascript or do I need to escape it before in PHP?
Edit: My script looks like this:
<script>
window.onload = function() {
thingiurlbase = "{#$__wcf->getPath('td')}js";
thingiview = new Thingiview("viewer");
thingiview.setObjectColor('#C0D8F0');
thingiview.initScene();
var url = "C:\\xampp\htdocs\\wcf2\\wcf/attachments/5d/18-5dffacdfe6d2cf1db8dfabbb5b53ae8dc65bd325";
thingiview.loadSTL(url);
thingiview.setRotation(false);
}
</script>
You need to escape the backslash characters.
var url = "C:\\xampp\\htdocs\\wcf2\\wcf/attachments/5d/18-5dffacdfe6d2cf1db8dfabbb5b53ae8dc65bd325";
Otherwise, JavaScript tries to interpret \x, \h, and \w as escaped special characters.
In this particular case, though, it looks like you could just replace the \ with / instead:
var url = "C:/xampp/htdocs/wcf2/wcf/attachments/5d/18-5dffacdfe6d2cf1db8dfabbb5b53ae8dc65bd325";
You need to escape backslashes.
var url = "C:\\xampp\\htdocs\\wcf2\\wcf/attachments/5d/18-5dffacdfe6d2cf1db8dfabbb5b53ae8dc65bd325";
If the string is printed from PHP, you can use addslashes to do the work for you.
$test = 'C:\xampp\htdocs\wcf2\wcf/attachments/5d/18-...';
echo $test . "\n";
echo addslashes($test);
>> C:\xampp\htdocs\wcf2\wcf/attachments/5d/18-...
>> C:\\xampp\\htdocs\\wcf2\\wcf/attachments/5d/18-...
Side Note
By the way, two things are incorrect with your approach:
The slashes in your string should all point the same way. If you want it to be used as a URL, use forward slashes e.g. http://stackoverflow.com/posts/17775495
If you want to give the browser a URL that it can use to access some resource on your server, this URL cannot be a file path (such as C:\xampp\htdocs\....) Instead, it has to be either relative to your site root, or an absolute URL (such as http://dropbox.com/my/file.pdf). Don't forget that a web user can only access files on your server through the web server.
Related
I am creating a dynamic regex but I have a problem with how to escape character so can one put some light on this?
I am using PHP with some backend configuration and admin can add regexp from backend to validate invalidate character and I am getting this value on the PHP so what I did
var regex = RegExp(<?php echo $regex ?>);
but I am getting the error like SyntaxError: Invalid regular expression: I know I need to escape the dynamic character but not sure how.
EDIT
I am trying this value from backend
<>{}[\]!##$+=%^*()/;
New EDIT
As per the #anubhava suggested I am escaping the special character by preg_quote() but on Regex.test it always fails I mean it always getting the false even though It should return true.
Here is my code,
var invalidCharRe = new RegExp(SOME_MY_VARIABLE);
var result = invalidCharRe.test(value)
Where SOME_MY_VARIABLE is a dynamic special character(which I am getting from PHP by preg_quote() and value is my textbox value
Since you're using php to echo your regex you can leverage php's preg_quote function to escape all special regex meta-characters beforehand like this:
var regex = /<?php echo preg_quote($regex, '/'); ?>/
Note that there is no need to call new RegExp here since Javascript will be always be getting a static string for regex.
I am working on a website that tracks which links the user has clicked. The data is stored as a string in localStorage. I know that string data in localStorage can be converted to JS objects by using JSON.parse. The problem is that the stored url strings contain characters that aren't valid for JSON. I am getting the error:
1_0.html:1 Uncaught SyntaxError: Unexpected token h in JSON at position 0
at JSON.parse (<anonymous>)
at trackLink (tracking_functions.js:318)
at HTMLAnchorElement.onclick (1_0.html:46)
I tried cleaning the string before sending it through the JSON parser using this suggestion but that didn't do the trick. And I am not sure if cleaning the string is even an option because it might make the url string unusable as a hyperlink.
Is there a way to get around this?
encodeURI() This function encodes special characters, except: , / ? : # & = + $ # (Use encodeURIComponent() to encode these characters).
encodeURIComponent() This function encodes special characters. In addition, it encodes the following characters: , / ? : # & = + $ #
You have to do it this way
var url = "https://a.but/#safe=active&q=sf";
var json = {"link": encodeURIComponent(url)}
localStorage.setItem("urls", JSON.stringify(json));
I'm making an Ajax call that sends a URL to a PHP script. Oftentimes these URLs are complex and contain special characters. If I don't encode the URL before sending, the PHP script works, but the URL's values are interpreted as my values (which is expected).
If I do encode a URL that doesn't contain special characters, like 'http://google.com' for example, the XMLHttpRequest sends my parameters to my PHP script as expected and everything works fine.
The issue is when I encode a URL that does contain special characters, like 'http://google.com?this=that&that=this' -- send() doesn't ever reach my PHP script. It just hangs indefinitely. No errors or anything. I'm stumped.
Here's what I'm working with:
function getContent(content, sumbittedUrl){
var postContent = encodeURIComponent(content);
var postUrl = encodeURIComponent(submittedUrl);
var postString = 'content=' + postContent + '&url_get=' + postUrl;
var httpRequest;
//create XMLHttpRequest
.
.
.
httpRequest.onreadystatechange = alertContents;
httpRequest.open('POST', 'php/my_php_script.php', true);
httpRequest.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
httpRequest.send(postString);
}
I'm a JavaScript novice so it's possible (likely, even) that I overlooked something that someone with more experience would spot quickly. Any help would be appreciated. Thanks.
I found a somewhat anti-climatic solution. I'm still unsure why encodeURIComponent() doesn't work as expected, but the less destructive encodeURI() is working fine. encodeURI() doesn't touch these characters: ; , / ? : # & = + $ so the URL's form stays intact. Potentially dangerous characters (e.g. < >) are still encoded.
The downside is that since ampersands are among the characters that don't get encoded, it means more work server-side to sort out incoming values.
EDIT:
It turns out it was a server-side issue after all. I was retrieving the values fine the whole time. The issue was with a cURL request using the aforementioned values. Don't trust PHP errors/warnings (or lack of them).
I want to send a few variables and a string with the POST method from JavaScript.
I get the string from the database, and then send it to a PHP page. I am using an XMLHttpRequest object.
The problem is that the string contains the character & a few times, and the $_POST array in PHP sees it like multiple keys.
I tried replacing the & with \& with the replace() function, but it doesn't seem to do anything.
Can anyone help?
The javascript code and the string looks like this:
var wysiwyg = dijit.byId("wysiwyg").get("value");
var wysiwyg_clean = wysiwyg.replace('&','\&');
var poststr = "act=save";
poststr+="&titlu="+frm.value.titlu;
poststr+="§iune="+frm.value.sectiune;
poststr+="&wysiwyg="+wysiwyg_clean;
poststr+="&id_text="+frm.value.id_text;
xmlhttp.open("POST","lista_ajax.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(poststr);
The String is:
<span class="style2">"Busola"</span>
You can use encodeURIComponent().
It will escape all the characters that cannot occur verbatim in URLs:
var wysiwyg_clean = encodeURIComponent(wysiwyg);
In this example, the ampersand character & will be replaced by the escape sequence %26, which is valid in URLs.
You might want to use encodeURIComponent().
encodeURIComponent(""Busola""); // => %26quot%3BBusola%26quot%3B
You need to url-escape the ampersand. Use:
var wysiwyg_clean = wysiwyg.replace('&', '%26');
As Wolfram points out, this is nicely handled (along with all the other special characters) by encodeURIComponent.
Ramil Amr's answer works only for the & character. If you have some other special characters, you should use PHP's htmlspecialchars() and JS's encodeURIComponent().
You can write:
var wysiwyg_clean = encodeURIComponent(wysiwyg);
And on the server side:
htmlspecialchars($_POST['wysiwyg']);
This will make sure that AJAX will pass the data as expected, and that PHP (in case your'e insreting the data to a database) will make sure the data works as expected.
You can pass your arguments using this encodeURIComponent function so you don't have to worry about passing any special characters.
data: "param1=getAccNos¶m2="+encodeURIComponent('Dolce & Gabbana')
OR
var someValue = 'Dolce & Gabbana';
data: "param1=getAccNos¶m2="+encodeURIComponent(someValue)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
You could encode your string using Base64 encoding on the JavaScript side and then decoding it on the server side with PHP (?).
JavaScript (Docu)
var wysiwyg_clean = window.btoa( wysiwyg );
PHP (Docu):
var wysiwyg = base64_decode( $_POST['wysiwyg'] );
The preferred way is to use a JavaScript library such as jQuery and set your data option as an object, then let jQuery do the encoding, like this:
$.ajax({
type: "POST",
url: "/link.json",
data: { value: poststr },
error: function(){ alert('some error occured'); }
});
If you can't use jQuery (which is pretty much the standard these days), use encodeURIComponent.
encodeURIComponent(Your text here);
This will truncate special characters.
For some reason, I am getting additional code in my encoded URI's with javascript encodeURIcomponent function, namely %25 character:
My function is:
function twit_click() {
var u="https://www.website.com/<?php echo $_SESSION['id'];?>";
var t="sometext";
window.open('http://www.twitter.com/share?url='+encodeURIComponent(u)+'&text='+encodeURIComponent(t),'twitsharer','toolbar=0,status=0,width=626,height=436');
return false;
}
when I click the text and call twit_click() function, I get the following URL:
http://twitter.com/intent/tweet?text=sometext&url=https%253A%252F%252Fwww.website.com%252Fuserid
as opposed to what it should be:
http://twitter.com/intent/tweet?text=sometext&url=https%3A%2F%2Fwww.website.com%2Fuserid
am I missing something? It is adding in additional "25" characters which would imply I have % in my URI which I clearly do not.
Remove the "www" from "www.twitter" and it works.
http://jsfiddle.net/tzkpz/
Twitter must be re-encoding the URL when it redirects from www.twitter.com to twitter.com, hence the double encoding.