How to escape "&" ampersand character in form input using jQuery How to escape "&" ampersand character in form input using jQuery codeigniter codeigniter

How to escape "&" ampersand character in form input using jQuery


htmlentites

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().

Example:

echo htmlentities("&"); // &

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

encodeURIComponent(string input);

Example:

encodeURIComponent($.trim($("input[name=t-tim_rendered-"+id+"]").val().toString()));


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.


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 + "'"