views:

765

answers:

3

I have a lot of JSON data I need to pass to a request:

$.ajax({
                type: "POST",
                url: "http://"+HOST+"/users/rankings",
                data: "friends="+JSON.stringify(friendsArr),
                success: function(response){
                    $("#rankings").html(response);
                }
            });

friendsArr is an array of objects in JSON format. The issue is that some objects have data with a "+" and that does not get encoded properly. It comes in server side as a " " and the data is messed up. Do I really have to iterate through all the data and encode each value separately? There must be an easier way.

+2  A: 

You should be able to use the javascript escape function to fix this problem. Just escape your data and URL before you send it off.

TM
no, i tried that.
Tony
@Tony what happens when you escape the data? The `+` still comes back as a space, or it comes back as something else? You'll probably have to decode it in your serverside code.
TM
correct, comes in as a " ". i am actually using rails so it should decode automatically...or else i think i would be getting some crazy errors
Tony
A: 

Isn't it as easy as:

$.ajax({
     type: "POST",
    url: "http://"+HOST+"/users/rankings",
    data: "friends="+escape(JSON.stringify(friendsArr)),
    success: function(response){
        $("#rankings").html(response);
    }
});
Harmen
doesn't work, i think it messes up the object
Tony
+3  A: 

I would try it using the $.post method vs. the raw $.ajax one, and let jQuery handle the work for you:

$.post( "http://"+HOST+"/users/rankings",
    { friends: JSON.stringify(friendsArr) },
    function(data){
        $("#rankings").html(response);
  }
);

Additionally, since you can only POST via AJAX to addresses on the same domain, why not just use "/users/rankings" as your URL vs. "http://"+HOST+"/users/rankings"

Doug Neiner
the post was not necessary (although not a bad idea) but doing friends: as opposed to "friends=" did it. i guess that tells jquery to escape the data and set the content-type properly... also thanks for reminding me about no need for domain!
Tony
+1 using the object for data is better than the string
TM