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
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 + "'"
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},
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()));
You could use 'encodeURIComponent' to accomplish the URL encoding for that component. I used this and validated with browsers IE, Firefox, and Chrome.
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.