$.ajax how to decode the sent data?

$.ajax how to decode the sent data?

I have a few input and textarea fields and when the submit button is pressed, I use $.ajax to send the data to a PHP script, which in turn, simply prints the data, which in turn is displayed in an alert msg box back in my callback. (The script will eventually load the data into a database but for simplification this is all it does for now).

The only problem, is that the $.ajax encodes/escapes special characters automatically and I can't figure out how to decode/unescape them to make them usable again. Here is the javascript (I simplified it to make it easy to understand):

$.ajax(
{
   url: 'my-ajax-script.php',
   type: 'POST',
   data: 'text=' + $('#myTextArea').val(),
   error: function()
   {
      alert('There is an error in this script');
   },
   success: function(msg)
   {
      alert(msg);
   }
});


Here is my php ajax script (super simple)
print $_POST['text'];


So anyways, everything appears to work fine. I enter some info into 'myTextArea', and press submit. The script sends it to the PHP script, which it turn returns the same value and the javascript puts it in a message box.

So the problem specifically is if I send special characters like any of the quotes ' " (single or double quotes). Lets say my text area had this text in it:

It's My "Birthday"


$.ajax sends the following data:

It\'s My \"Birthday\"


So how do I unescape this? Ya, I could simply replace all backslashes, but I assume there are other characters it may escape in special ways I'm not sure about. What is the proper way to do it?

The only possible way I could figure out to do this was to use

escape($('#myTextArea').val())


So the data gets sent as:

It%27s%20My%20%22Birthday%22


And then use the PHP command "urldecode" on the other end. It turns out correct that way. However, that doesn't seem like the proper way to do it. Javascript 'escape' command was meant for escaping characters for sending GET variables and for sending formatted URLs. Not for text and input forms. Is there a better/more proper way?

What am I missing?
    • Topic Participants

    • mike