0

I am making a basic PATCH call like this one:

.ajax({
    url: "/foo/bar/"
    type: "PATCH",
    dataType: 'json',
    data: {
        "foo": "foosball",
        "bar": "bars on bars"
    },
    ...
});

Jquery automatically encodes the data, which leaves "bars on bars" like "bars+on+bars". Is there a way to change the encoding so that spaces are replaces with %20 rather than pluses?

I've noticed this thread that didn't seem to lead anywhere.

I've also taken note of encodeURI and encodeURIComponent but haven't gotten either to work. Both seem to result in the string being double encoded, leaving me with bars%2520on%2520bars

summary:

What I start with: ... "bars on bars" ...

What the received data looks like after jquery encodes the request: "bars+on+bars"

What I need the received data to look like: "bars%20on%20bars"

6
  • How about "bar": encodeURIComponent("bars on bars") ? Commented Jun 17, 2016 at 4:32
  • For some reason that double encodes it and leaves me with bars%2520on%2520bars Commented Jun 17, 2016 at 4:43
  • What are u using PATCH for ? How you access on url page Commented Jun 17, 2016 at 4:46
  • The endpoint accepts PATCH requests. Does jquery encode differently for different http methods? Commented Jun 17, 2016 at 5:00
  • Yeah, because double encode here: space -> %20, and then %20 -> %2520. Maybe you can process data manually and set processData: false. Commented Jun 17, 2016 at 5:01

2 Answers 2

1

How about use a variable and pass that to data.

var d={
    "foo": "foosball",
    "bar": "bars on bars"
}
d.bar=encodeURI(d.bar);

.ajax({
url: "/foo/bar/"
type: "PATCH",
dataType: 'json',
data: d,
...
});
Sign up to request clarification or add additional context in comments.

5 Comments

I updated the question, but encodeURI and encodeURIComponent double encodes the data, which leaves me with bars%2520on%2520bars.
have you tried adding contentType: application/json ?
Yes, still pluses though :(
shooting in the dark... data: JSON.stringify({"foo": "foosball","bar": "bars on bars"})
Yes, I've been looking at that and I think I might just have to use that. It requires converting it from a string to a dict/json once received though.
0

Still wish there was a better way, but I ended up using this plugin from this website.

 jQuery.extend({
     postJSON: function(url, data, callback) {
         return jQuery.ajax({
             type: "POST",
             url: url,
             data: JSON.stringify(data),
             success: callback,
             dataType: "json",
             contentType: "application/json",
             processData: false
         });
      }
  });

This forces my api to parse the body as a string into a dict/json. Hopefully in a few years someone can come along with a better solution.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.