AJAX POST requests with JQuery don't urlencode '+'

10,225

Solution 1

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"

Solution 2

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.

Solution 3

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);
    }
});
Share:
10,225
Abhinav Kaushal Keshari
Author by

Abhinav Kaushal Keshari

Updated on June 18, 2022

Comments

  • Abhinav Kaushal Keshari
    Abhinav Kaushal Keshari almost 2 years

    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.