Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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}
like image 377
Will Curran Avatar asked Dec 28 '22 01:12

Will Curran


2 Answers

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 }}
like image 101
Ignacio Vazquez-Abrams Avatar answered Dec 30 '22 15:12

Ignacio Vazquez-Abrams


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

I hope this helps!

like image 21
used2could Avatar answered Dec 30 '22 13:12

used2could