Fix plus sign (+) is replaced with space using ajax

Fix plus sign (+) is replaced with space using ajax

Code Snippet
  1. DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4. <title>Fix plus sign (+) is replaced with space using ajaxtitle>
  5. <meta name="author" content="http://123code.blogspot.com" />
  6. <script src="js/jquery-1.2.6.pack.js" type="text/javascript">script>
  7. <script type="text/javascript">
  8. function update() {
  9. var comment = $('#txtComment').val();
  10. $.ajax({
  11. type: 'POST',
  12. data: 'comment=' + encodeURIComponent(comment),
  13. success: function(data) {
  14. $('#result').html(data);
  15. }
  16. });
  17. return false;
  18. }
  19. script>
  20. head>
  21. <body>
  22. <form id="form1">
  23. <div>
  24. <h1>Fix plus sign (+) is replaced with space using ajaxh1>
  25. <input id="txtComment" type="text" />
  26. <input id="btnUpdate" type="button" value="button" onclick="return update();" />
  27. div>
  28. <div>Result:div>
  29. <div id="result">div>
  30. form>
  31. body>
  32. html>

In line 13, i use encodeURIComponent to solve the problem. To see the problem, just replace encodeURIComponent with escape function.

Ps: Don't trust user input. The data should be encoded before sending to server side. I don't know why the browsers replace plus sign (+) with space using escape function, please let me known.

Happy coding!

Comments