0

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!

qalbiol
  • 475
  • 7
  • 21

3 Answers3

2

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.

Community
  • 1
  • 1
bjb568
  • 11,089
  • 11
  • 50
  • 71
  • 2
    Note that `encodeURIComponent`) is correct (not `encodeURI`): *Note that **encodeURI by itself cannot form proper HTTP GET and POST requests**, such as for XMLHTTPRequests, **because "&", "+", and "=" are not encoded**, which are treated as special characters in GET and POST requests. encodeURIComponent, however, does encode these characters.* [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI) – Jared Farrish Apr 05 '14 at 18:02
1

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.

Peteris
  • 3,281
  • 2
  • 25
  • 40
0

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.

naota
  • 4,695
  • 1
  • 18
  • 21