Dail
Dail

Reputation: 4606

How to encode text using jquery?

I'm using ajax() to send POST request to a php page. This is the code:

  date     = $.trim($('#date').val()) 
  expiry   = $.trim($('#expiry').val()) 
  priority = $.trim($('#priority').val()) 
  note     = $.trim($('#note_text').val())

  $.ajax({
    type: "POST",
    url:  "client?method=addNote&id=10",
    data: "date="+date+"&expiry="+expiry+"&priority="+priority+"&note="+note,
    success: function(msg){
      alert(msg);
    }
  });

my problem is that the last variable named note could has many "strange" characters, like: & % $ / : ; , .

I have seen that the php page is no receiving all the "note" string correctly. If it found (&) it js "truncate" the string. how could I encode that text?

Upvotes: 2

Views: 6548

Answers (2)

pgl
pgl

Reputation: 7981

Try:

note = encodeURIComponent($.trim($('#note_text').val()));

See here for more on encodeURIComponent: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/encodeURIComponent

Upvotes: 1

Quentin
Quentin

Reputation: 943108

Don't pass a string, just pass the data.

data: { date: date, expiry: expiry, priority: priority, note: note },

If you were to pass a string, then you are building a URI by hand and that has nothing to do with jQuery, so you would use encodeURIComponent.

Upvotes: 4

Related Questions