31

I am performing asynchronous HTTP (Ajax) requests via jQuery with the basic $.ajax(). The code looks like the following:

$("textarea").blur(function(){
   var thisId = $(this).attr("id");
   var thisValue = $(this).val();

   $.ajax({
      type: "POST",
      url: "some.php",
      data: "id=" + thisId + "&value=" + thisValue,
      success: function(){
        alert( "Saved successfully!" );
      }
   });

});

Everything is working properly as usual, until user types inside textarea ampersand (&) character. Than when I debug PHP function, which saves the value, it always have a value until this character.

I believe there has to be a solution to skip ampersand (&) somehow. Any ideas?

Makoto
  • 104,088
  • 27
  • 192
  • 230
Nik Sumeiko
  • 8,263
  • 8
  • 50
  • 53

4 Answers4

88

Instead of:

data: "id=" + thisId + "&value=" + thisValue

do:

data: { id: thisId, value: thisValue }

This way jquery will take care of properly URL encoding the values. String concatenations are the root of all evil :-)

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
30

Strongly recommend you use the solution provided by Darin above if at all possible; that way, you get to reuse well-tested code for building POST data.

But if you really, really, really need to use string concatenation (here, or elsewhere in your application when building up query strings or POST data out of user inputs), you need to use encodeURIComponent:

$("textarea").blur(function(){
   var thisId = $(this).attr("id");
   var thisValue = $(this).val();

   $.ajax({
      type: "POST",
      url: "some.php",
      data: "id=" + encodeURIComponent(thisId) + "&value=" + encodeURIComponent(thisValue),
      success: function(){
        alert( "Saved successfully!" );
      }
   });
});

By default when sending a POST with jQuery.ajax, you're sending data with the content type application/x-www-form-urlencoded, which means you're promising that the data is encoded that way. You have to be sure to keep your part of the bargain and actually encode it. This isn't just important for ampersands.

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • +1 for explaining _why_ the error occurred and how to fix it as is. – sholsinger Nov 19 '10 at 15:55
  • I actually tried this and it didn't work. I also tried replacing `&` with `&` and that did nothing aswell, surprisingly. – Eduard Luca Oct 19 '12 at 19:36
  • 1
    @EduardLuca: *"I actually tried this and it didn't work."* You'd have to give some specifics (probably in your own question);`encodeURIComponent` **is** the correct way to do this. *"I also tried replacing & with & and that did nothing aswell, surprisingly"* Actually not surprising, as that's HTML entity encoding which has nothing whatsoever to do with URI encoding. – T.J. Crowder Oct 19 '12 at 22:51
  • Exactly, `&` is a HTML entity, so it shouldn't take it as part of the URL, but as part of the string inside the URL params. When I said "I tried this" I actually meant I tried exactly your solution with `encodeURIcomponent` on all fields, and it had no effect whatsoever. – Eduard Luca Oct 19 '12 at 22:56
  • 1
    @EduardLuca: *"Exactly, & is a HTML entity, so it shouldn't take it as part of the URL, but as part of the string inside the URL params."* Huh? Computers don't guess at how things are encoded (usually). If you include it in the URL, then the server will treat it as URI-encoded, because that's how URIs are defined. If you include it in form data in a POST, it will be treated as URI-encoded, because that's how *that* is defined. Again, without showing your specific situation (and that would suggest you need to post a question, not a comment), "it had no effect" has exactly no meaning. – T.J. Crowder Oct 19 '12 at 23:36
  • OK, nevermind, I was just trying to point something out, but I guess it got personal for you or something. I've long fixed it using Darin Dimitrov's answer. – Eduard Luca Oct 19 '12 at 23:39
  • @EduardLuca: No, nothing personal. I just don't see what you're saying, and don't see how others could based on what you've posted either. I'm big into data, evidence, that kind of thing. Sorry if I came off in some other way. (And for the record: All Darin's answer does -- and it's a good answer, that's how I do it -- is offload the call to `encodeURIComponent` to jQuery's code. The net result is the same.) – T.J. Crowder Oct 19 '12 at 23:42
  • I love you! I spend hours trying to figure out why the frak the ambersand was stripped on posts... thank you! – Spock Jul 10 '13 at 07:31
6

just use the javascript function encodeURIComponent():

$("textarea").blur(function(){
   var thisId = $(this).attr("id");
   var thisValue = $(this).val();

   $.ajax({
      type: "POST",
      url: "some.php",
      data: "id=" + thisId + "&value=" + encodeURIComponent(thisValue),
      success: function(){
        alert( "Saved successfully!" );
      }
   });

});
js1568
  • 7,012
  • 2
  • 27
  • 47
0
$.ajax({

   type:'POST',
 dataType: "text",
   url:'save.php',
   data:'_id='+$('#id').val()+'&title='+$('#title').val(),
??
data: { id: thisId, value: thisValue }
Rahil Wazir
  • 10,007
  • 11
  • 42
  • 64