Skip to content
Advertisement

How to send data in request body with a GET when using jQuery $.ajax()

The service API I am consuming has a given GET method that requires the data be sent in the body of the request.

The data required in the body is a list of id’s separated by hypen and could potentially be very large and thus it must be sent in the body otherwise it will likely foobar somewhere in the browsers/proxies/webservers etc chain. Note I don’t have control over the service or API so please don’t make suggestions to change it.

I am using the following jQuery code however observing the request/response in fiddler I can see that the “data” I am sending is ALWAYS converted and appended to the query string despite me setting the “processData” option to false…

$.ajax({
   url: "htttp://api.com/entity/list($body)",
   type: "GET",
   data: "id1-id2-id3",
   contentType: "text/plain",
   dataType: "json",
   processData: false, // avoid the data being parsed to query string params
   success: onSuccess,
   error: onError
});

Anyone know how I can force the “data” value to be sent in the body of the request?

Advertisement

Answer

In general, that’s not how systems use GET requests. So, it will be hard to get your libraries to play along. In fact, the spec says that “If the request method is a case-sensitive match for GET or HEAD act as if data is null.” So, I think you are out of luck unless the browser you are using doesn’t respect that part of the spec.

You can probably setup an endpoint on your own server for a POST ajax request, then redirect that in your server code to a GET request with a body.

If you aren’t absolutely tied to GET requests with the body being the data, you have two options.

POST with data: This is probably what you want. If you are passing data along, that probably means you are modifying some model or performing some action on the server. These types of actions are typically done with POST requests.

GET with query string data: You can convert your data to query string parameters and pass them along to the server that way.

url: 'somesite.com/models/thing?ids=1,2,3'
Advertisement