how to escape ampersand character in form input using jquery

how to escape ampersand character in form input using jquery  using -'php,jquery,ajax,codeigniter'

I have a problem with my jQuery script that send data via POST method. The problem is whenever it sends data via Ajax that has an "&" ampersand in the sentence, it will cut the sentence when found "&".

Please check the images below for more info.


asked Sep 15, 2015 by NaomiWaters
0 votes

5 Answers

0 votes


This function is identical to htmlspecialchars() in all ways, except with htmlentites(), all characters which have HTML character entity equivalents are translated into these entities.

If you're wanting to decode instead (the reverse) you can use html_entity_decode().


echo htmlentities("&"); // &

if your directly doing this in the browser you should be able to use:

encodeURIComponent(string input);


answered Sep 15, 2015 by KarolynHPZIk
0 votes

I've been having a huge problem exactly with this situation.

This is just to say that the last answer from Andrew Koester is the perfect answer I was looking for.

In case you are passing multiple form entries from a jQuery form to PHP through the .ajax() call like this:

data: "name=" + name + "&message=" + message + ...

DON'T USE THIS METHOD, it will block the ampersand(&) character from being written by the user on any of the input fields of your form.

Use this one instead as suggested by Andrew:

data: {"name": name, "email": email, "subject": subject, "comments": comments},

This way the user can write any kind of special character whithout worrying a about conflicting with the ajax declaration.

answered Sep 15, 2015 by DuaneUtzcild
0 votes

If you pass your data parameter as a Javascript object, it will convert the characters for you (and IMO make the code look neater). So you should change your $.ajax call to the following:

data: {"user_id": user_id, "time_r": time_r, "task_d": task_d, "p_id": p_id, "df": finished},
answered Sep 15, 2015 by ArethaRadke
0 votes

You can use a native javascript escape() function

In line 74

data: : "&task_d=" + escape(task_d) + "" 

Alternatively, you could enclose your query string values in quotes

data: : "&task_d='" + task_d + "'" 
answered Sep 15, 2015 by Qui6895
0 votes

You could use 'encodeURIComponent' to accomplish the URL encoding for that component. I used this and validated with browsers IE, Firefox, and Chrome.

answered Sep 15, 2015 by GenieEspej