Will Curran
Will Curran

Reputation: 7110

How to escape special characters in query string sent via JQuery ajax function?

I need to POST short messages to the server. Sometimes they have special characters, like in this example:

&message=Joining a game of Commands & Colors: Ancients.

How do I escape special characters from a query string?

I'm using Django. Here's the field I need to encode:

<textarea class="text-area" id="message" name="message" rows="3" cols="30">
   Joining a game of {{ game.name }}.
</textarea>

UPDATE: I realize that the POST is going through JQuery's ajax function:

  $("#checkin-button").click(function() { 
          var mid = $("input#mid").val();
          var message = $("textarea#message").val();
          var facebook = $('input#facebook').is(':checked');
          var name = $("input#name").val();
          var bgg_id = $("input#bgg-id").val();
          var thumbnail = $("input#thumbnail").val();
          var dataString = 'mid='+mid+'&message='+message+'&facebook='+facebook+'&name='+name+'&bgg_id='+bgg_id+'&thumbnail='+thumbnail;  
    $.ajax({  
      type: "POST",  
      url: "/game-checkin",  
      data: dataString,  

So I'm not passing that correctly (urlencoded) right?

UPDATE: after realizing the issue was with JQuery, I was able to fix it by replacing the data variable assignment with:

    data: {"mid": mid, "message": message, "facebook": facebook, 
"name": name, "bgg_id": bgg_id, "thumbnail": thumbnail}

Upvotes: 4

Views: 4940

Answers (3)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798884

Python:

>>> urllib.urlencode({'message': 'Joining a game of Commands & Colors: Ancients.'})
'message=Joining+a+game+of+Commands+%26+Colors%3A+Ancients.'

Django:

message={{ message|urlencode }}

Upvotes: 7

Victor
Victor

Reputation: 17097

Take a look at this: http://www.blooberry.com/indexdot/html/topics/urlencoding.htm

So : becomes %3A
BTW...most modern browsers do this automatically.

Upvotes: 0

Brian
Brian

Reputation: 4984

import urllib;
urllib.urlencode("string");

I hope this helps!

Upvotes: 3

Related Questions