Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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? Any assistance is appreciated, thanks in advance.

like image 467
Oliver Pearmain Avatar asked Apr 24 '12 13:04

Oliver Pearmain


People also ask

Can we send data in request body with get?

So, yes, you can send a body with GET, and no, it is never useful to do so. This is part of the layered design of HTTP/1.1 that will become clear again once the spec is partitioned (work in progress). Yes, you can send a request body with GET but it should not have any meaning.

Can we send data in Ajax GET request?

The jQuery. get( url, [data], [callback], [type] ) method loads data from the server using a GET HTTP request. data − This optional parameter represents key/value pairs that will be sent to the server.


1 Answers

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' 
like image 190
EndangeredMassa Avatar answered Oct 09 '22 03:10

EndangeredMassa