I have the following code:
var artist = document.getElementById("txtBoxArtist").value;
When value is plain text, e.g. Biffy Clyro, artist = Biffy Clyro
When value contains &, e.g. Mumford & Sons, artist = Mumford
I the send artist value using AJAX, and recover the value on another php page like this:
var data = "nameTitle=" + title + "&nameArtist=" + artist;
[...]
$nameArtist=$_POST['nameArtist'];
Why does this happen and how to avoid it? It is giving me lots of problems this &symbol...
Thank you all!
You need to encode the values before sticking them on the URL.
var data = "nameTitle=" + encodeURIComponent(title) + "&nameArtist=" + encodeURIComponent(artist);
You should also see this.
Some characters are special and need 'escaping' to encode their values - as you are showing using & instead of &.
However, these escaping principles are different for HTML content and for URLs/URIs.
In URI, & is escaped as %26 and not as & - so you should either use that or the appropriate encoding/decoding functions, not the HTML entity encoding/decoding.
I guess you can encode valiables before sending them like this:
artist = encodeURIComponent(artist);
title = encodeURIComponent(title);
var data = "nameTitle=" + title + "&nameArtist=" + artist;
hope this helps.
Related
I have a variable written from PHP into my javascript (using json_encode), that looks a little like this:
mappoints[x]['about'] = 'Administrator: Foo Barlt;br />Telephone: 555-4202<br />Email: bert#hotmail.com<br />Website: www.domain.com'
That I am using for a google maps map point. Using the json_encode seems to be very picky about what characters I can and cannot enter into it, so i am wondering how I can convert those special html characters into real html characters using javascript?
update
The way i am building my variable is:
var description = "<h3 style='margin: 0; padding: 0;'>" + mappoints[x]['name'] + "</h3><b>Director:</b> " + mappoints[x]['director'] + "<br/>" + mappoints[x]['about'];
The HTML in the varaible is all fine, until I add the about index. No function I have attached or tried yet seems to give me proper HTML.
You can use the dom to decode those entities for you.
mappoints[x]['about'] = 'Administrator: Foo Barlt;br />Telephone: 555-4202<br />Email: bert#hotmail.com<br />Website: www.domain.com'
mappoints[x]['about'] = $('<div/>').append(mappoints[x]['about']).text();
http://jsfiddle.net/5FTCX/
Basically when you add the html to the dom it will show the entities as the characters they represent, using .text() you can receive the data back as you'd see it in the browser as text, not html with the entities. If you want back the html you can use .html() e.g..
Would it be okay with :
return mystring.replace(/&/g, "&").replace(/>/g, ">").replace(/</g, "<").replace(/"/g, """);
From here : Convert special characters to HTML in Javascript
Just because #Musa's idea was great but needed some re-interpreting on my side, I wish to post a quick function here, that will handle htmlspecialchars great, based on #Musa's design :
function htmlspecialchars_decode(string) {
$('body').append("<span style='display:none;visibility:hidden;' id='tempText'>" + string + "</span>");
var result = $('#tempText').text();
$('#tempText').remove();
return result;
};
try this
decodeURIComponent(str) or `unescape(str)` or `decodeURI(str)`
I have one one hidden paramter in form whose value is
custAddress=CustomerAddress.do?fisrtName=scott&lastName=Miles
I want to encode it before sending it and so that characters like & can be replaced with %26 etch
i tried using javascript built-in encodeURI("urlToencode") but does not encode characters like &?
Try this code line,
encodeURIComponent("fisrtName=scott&lastName=Miles");
Use https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/encodeURIComponent
You need to call that on each dynamic part (name and value) of the URL query string. So the question is what is the URI component in custAddress=CustomerAddress.do?fisrtName=scott&lastName=Miles That doesn't really look like a URL because you have the = before the ?
The most sense that I can make is that the full URL is something like
http://myserver/file.do?custAddress=CustomerAddress.do?fisrtName=scott&lastName=Miles
In which case, you should build your URL like
var custAddress = "CustomerAddress.do?fisrtName=scott&lastName=Miles";
var initialPath= "/path/to/file.do?";
var url = initialPath + "custAddress=" + encodeURIComponent(custAddress);
Since you mentioned jQuery, you can use a $.param, looks cleaner and does the encoding for you, and you can give it multiple query parameters at once
var url = initialPath + $.param({
custAdrress: custAddress,
otherParam: "paramVal",
// Both the param name and value need to be encoded and $.param does that for you
"funny Name & Param": "funny & value ="
});
I'm trying to insert a variable's value into a url, but it's not working; I'm just getting the variable not the value
'myid' and 'verif' are the variables and their values are integers.
This code inserts the url into a hidden field in a form
$('#return').val(http://pegdown.com/index.php?option=com_joom_creditspack&controller=paypal&view=paypal&layout=return&task=checkout&myid=myid&packid=1&verif=verif&jcode=xxx111xxx);
How do I write the following url so the variables 'myid' and 'verif' are converted to their values?
Well you are missing quotes so your code would not work at all.
$('#return').val("http://pegdown.com/index.php?option=com_joom_creditspack&controller=paypal&view=paypal&layout=return&task=checkout&myid=" + myid + "&packid=1&verif=" + verif + "&jcode=xxx111xxx");
You should probably use encodeURIComponent()
You need to quotes " " the strings and concat the variables +
Try
$('#return').val("http://pegdown.com/index.php?option=com_joom_creditspack&controller=paypal&view=paypal&layout=return&task=checkout&myid="+myid+"&packid=1&verif="+verif+"&jcode=xxx111xxx");
JavaScript does not support string interpolation. Try something like this.
myIdVal = encodeURIComponent(myId);
verifVal = encodeURIComponent(verif);
var url = "http://pegdown.com/index.php?option=com_joom_creditspack&controller=paypal&view=paypal&layout=return&task=checkout&myid=" + myidVal + "&packid=1&verif=" + verifVal + "&jcode=xxx111xxx";
$('#return').val(url);
A simple string works for me:
given index = 2,
`a.setAttribute("href", "myDirectory/" + index + ".jpg");` links the anchor to
"myDirectory/2.jpg", ie. the file number is taken from variable index.
Not sure if the setAttribute tolerates multiple tokens in its second parameter, but generally, this works.
I am unable to send data through my ajax call if the user put quotes in the textarea. Is there a way to send text with quotes? I dont want to get rid of the quotes. I guess this is usually not a big problem, i found very little online about this situation.
var description = $('#Description').val();
var title = $('#Title').val();
var parameters = '{content:' + $('#ContentCheck').is(':checked') +
',title: "' + title + '",desciption:"' + description + '"}';
Checkout JSON.stringify(object) which is built into javascript.
The jist is, you create a javascript object, and call stringify to create a JSON string. With your information given above, you might do:
var jsonText = JSON.stringify({
'content': $('$('#ContentCheck').is(':checked'),
'title': title,
'description': description
});
Here we define a javascript hash using the curly braces, and then pass it to stringify.
same problem was with me.I tried this and completely working
xmlhttp.open("POST","test_test.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("name="+encodeURIComponent(name)+"&details="+encodeURIComponent(details)+"&r_price="+r_price+"&o_price="+o_price+"&id="+id);
and use urldecode($_REQUEST['details'])` when inserting.
You can convert parameters into a map -- basically an associative array -- instead of a string. That way, you can do string manipulation in the backend .NET without any changes in your frontend js; e.g.
var url = 'http://path/to/your/backend/script';
var parameters = {
contentCheck: $('#ContentCheck').is(':checked'),
title: title,
description: description
};
$.post(url, parameters);
You can encode quotes using js and decode it server side to get the original string
//js
function totalEncode(s){
str= s.replace(/\&/g,'&');
str= str.replace(/</g,'<');
str= str.replace(/>/g,'>');
str= str.replace(/\"/g,'"');
str= str.replace(/\'/g,''');
return(str);
}
I have a JavaScript function like so:
var strBody = encodeURI(window.location.href);
var strSubject = encodeURI(document.title);
var mailto_link = "mailto:?subject=" + encodeURI(strSubject) + "&body=" + strBody;
This code is executed on a hyperlink's onclick event, and opens the mail client (mailto://). However, the title of the page has several & symbols, but the title is only picked up until the first &. The url is always picked up.
What is the correct JavasSript to escape the & and display it in the mail client's subject line?
var encoded_body = encodeURIComponent(window.location.href);
var encoded_subject = encodeURIComponent(document.title);
var mailto_link = "mailto:?subject=" + encoded_subject + "&body=" + encoded_body;
should do it (encodeURIComponent instead of encodeURI).
In your original code you were also incorrectly double encoding the subject (once on line 2, and then again on line 3).
I took the liberty of renaming your variables to make it clearer that they contain the encoded subject and body, as opposed to the original text.
You want encodeURIComponent not encodeURI.