CancelImage Upload

Ajax Forms and how to save or print + and other special symbols successfully

Sending special characters such as plus symbols through an AJAX form to be received the other end requires a bit of trickery. Often when programmers experience trouble with this kind of transmissions there was either

  1. A lack of encoding on the JavaScript side.
  2. The decode function on the PHP side was not good enough.
  3. No encoding took place on either side.
  4. No encoding took place on one of the two sides.
So, what is all this talk about encoding? Well you see, as with get variables, Ajax can not pass along un-encoded information successfully. For instance you could not pass along a url such as

http://www.example.com/index.php?page=D260&id=22

successfully without turning it into an encoded format which can be passed along without causing any problems:

http%3A%2F%2Fwww.example.com%2Findex.php%3Fpage%3D260%26id%3D22

Now, to perform this little bit of magic in JavaScript we can use the following piece of code:

var poststr = "get1=" + encodeURIComponent( document.getElementById("id1").value );

Note that encodeURIComponent() is the key in the above code. This little bit of formatting has solved half our problem. However, we still need a function to effectively decode the variable on the server side end of things. In PHP, most tutorials will tell you to decode the variable using urldecode():

$string = urldecode($_POST['variable']);

And while urldecode() is a capable function, it has not got the correct search pattern within it to translate the + symbols passed along via Ajax after being translated with the JavaScript function encodeURIComponent(). Lucky for us however a pre defined PHP function does exist which can translate the plus symbol, no matter if it was passed along as %20 or %2A. This function is rawurldecode():

$string = rawurldecode($_POST['variable']);

With rawurldecode() your plus symbols and (most) other special symbols should be translated successfully.

Login
Want to leave a comment?

No problem. Just enter your email and password below.


register | home | reminder

myDesignTool Networking • www.mydesigntool.cominfo@mydesigntool.com