Get jQuery $.ajax to send data in body for GET [duplicate] - javascript

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?

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'

we all know generally that for sending the data according to the http standards we generally use POST request.
But if you really want to use Get for sending the data in your scenario
I would suggest you to use the query-string or query-parameters.
1.GET use of Query string as.
{{url}}admin/recordings/some_id
here the some_id is mendatory parameter to send and can be used and req.params.some_id at server side.
2.GET use of query string as{{url}}admin/recordings?durationExact=34&isFavourite=true
here the durationExact ,isFavourite is optional strings to send and can be used and req.query.durationExact and req.query.isFavourite at server side.
3.GET Sending arrays
{{url}}admin/recordings/sessions/?os["Windows","Linux","Macintosh"]
and you can access those array values at server side like this
let osValues = JSON.parse(req.query.os);
if(osValues.length > 0)
{
for (let i=0; i<osValues.length; i++)
{
console.log(osValues[i])
//do whatever you want to do here
}
}

Just in case somebody ist still coming along this question:
There is a body query object in any request. You do not need to parse it yourself.
E.g. if you want to send an accessToken from a client with GET, you could do it like this:
const request = require('superagent');
request.get(`http://localhost:3000/download?accessToken=${accessToken}`).end((err, res) => {
if (err) throw new Error(err);
console.log(res);
});
The server request object then looks like {request: { ... query: { accessToken: abcfed } ... } }

You know, I have a not so standard way around this. I typically use nextjs. I like to make things restful if at all possible. If I need to make a get request I instead use post and in the body I add a submethod parameter which is GET. At which point my server side handles it. I know it's still a post method technically but this makes the intention clear and I don't need to add any query parameters. Then the get method handles a get request using the data provided in the post method. Hopefully this helps. It's a bit of a side step around proper protocol but it does mean there's no crazy work around and the code on the server side can handle it without any problems. The first thing present in the server side is if(subMethod === "GET"){|DO WHATEVER YOU NEED|}

Related

Execute a python function without response - Django [duplicate]

This question already has answers here:
How do I send empty response in Django without templates
(2 answers)
Closed 3 years ago.
I'm working with Django in a project and I need to execute some functions depending on what user's want to do. If this action has to return and show new values I know how to do it, but when I just want to execute a function in my views.py that I don't need any response and don't know how to do it.
Now what I'm doing is return something and don't use it, but I'm sure it is possible do it without returning anything.
My code that returns a response is:
$('#import_btn').click(function(){
updateData()
});
function updateData(filt){
console.log('Hello');
var csrftoken = $("[name=csrfmiddlewaretoken]").val();
$.ajax({
url: '/../../updateBBDD/',
type: 'POST',
headers:{"X-CSRFToken": csrftoken},
data: {
'Filt': filt,
},
dataType: "json",
cache: true,
success: function(response) {
var cols = response.Cols;
}
});
}
How I have to do it in my js to execute a python function with no response??
Thank you very much.
I think you overcomplicate things. The HTTP protocol [wiki] is a request-response protocol. So normally, each request is followed by a response. That response can be empty, denote a problem, etc.
You thus can define a view function that does something, and returns an empty HttpResponse object [Django-doc]:
# app/views.py
from django.http import HttpResponse
def some_view(request):
# … do something …
return HttpResponse()
Your front-end code (js) doesn't know anything about Python - all it's doing is sending an HTTP request to a given url (and it of course expects a response - that's the very basis of HTTP). The fact that this request actually triggers the execution of some Python code is totally orthogonal - as far as your js code is concerned, the response could also just be Apache or nginx etc returning a file's content, or some proxy server returning a response from a cache, etc.
So on the front side, your js code sends a request and it expects a response (whatever the response content is). This tells the j code that the request has been received and processed one way or another.
On the Python/Django side, a Django "view" is a "request handler" - a callable (function, method or else) that takes an incoming request and returns a response. Note that this last part is mandatory - if your view doesn't return a response, you'll get an exception. What this response contains is up to you (the content can be totally empty), but you must return it.
Note that even if the response content is actually empty, the response will always hae a status code (200 being the default) telling the client (your js code or whatever) whether the request was "correctly" handled or if anything went wrong. So you probably don't want to ignore the response's status_code (at least) in your client code, nor blindly return a 200 whatever happened in the backend - if something didn't worked as expected, you certainly want to notify the user...
Given your question, I strongly suggest you read the HTTP specs. Trying to do web programming without a decent understanding of the protocol isn't going to yield great results...

Using POST and GET to Exchange Data Through Endpoints

I'm attempting to build a web app using Spotify's web API however, I find their tutorial lacking. The way it works is data is requested using POST and GET functionality and sent back using JSON. Seems easy enough, want to get information about an artist? Just call GET https://api.spotify.com/v1/artists/0OdUWJ0sBjDrqHygGUXeCF and you get a nice JSON document with information about the requested artist.
The problem is I don't know how to make that GET call. jQuery has get and post methods both with "data" parameters but I'm not sure on the syntax necessary, especially when it comes to exchanging an authorization code for an access token. If you visit Spotify's authorization guide and scroll to step 4 of the Authorization Code Flow you can see I need to make a POST call to https://accounts.spotify.com/api/token. The call must have 3 request body parameters and 1 header parameter and upon succession a JSON file with the appropriate data is in the response body.
My question is how do I make POST and GET calls that have body parameters and header parameters and how do I extract the JSON data from the response body after a successful call?
As you can see from their code examples & libraries and this jsFiddle, their getUserData request is nothing but a simple ajax call, which contains their url and a headers object (which contains a prefix string concatenated with the accessToken) as parameters:
function getUserData(accessToken) {
return $.ajax({
url: 'https://api.spotify.com/v1/me',
headers: {
'Authorization': 'Bearer ' + accessToken
}
});
}
Generally, when you need to pass parameters in an $.ajax call, just do as shown above, or construct an object first and include it like this:
YourObj = {
url: "your url here",
param2: "param val 2",
param3: "param val 3",
...
}
$.ajax(YourObj).done(function(data){
//do something with the returned data here, e.g.
console.log("data: ", data);
});
This approach can be useful if your parameters are dependent on other values which are not so readily avalable.

Need to get serialized data from a form

I'm new to prototypejs. Can you guys tell me how to get serialized values from a posted form using Ajax in prototype?
http://www.prototypejs.org/api/ajax/request
Is this what you need?
http://prototypejs.org/api/form/serialize
Or you want to handle a form through ajax instead of page load? then
http://prototypejs.org/api/form/request
"how to get serialized values from a posted form using Ajax " Makes it sound like you're expecting the Ajax response to include the serialized data sent to the server, but what the response contains is entirely up to the server. Typically, once you make an Ajax request, the onComplete handler doesn't really care about the properties that it sent. The response argument to the onComplete (and any other Ajax callback) contains a request property, which contains parameters object. This would be useful if you did indeed need to see what your request sent to the server, like so:
$('customerdetails').request({
method: 'get',
onComplete: function(response) {
console.log(response.request.parameters); // What you sent to the server
console.log(response.responseText); // What the server sent back to you
console.log(response.responseJSON); // JSON-ified version of what the server sent back
}
});
It's possible for response.responseJSON to be null if Prototype isn't sure that the response actually contains JSON (if, for instance, the response headers were improperly set). If you can bank on the response being JSON, you could do something like this:
onComplete: function(response) {
var jsonObj = response.responseJSON || response.responseText.evalJSON();
// now you can work with jsonObj
}
Hope this helps and I didn't just completely misunderstand your question.
new Ajax.Request('your_ajax_url',{
method:'POST',
parameters:Form.serialize($('your_form_id'))
});

How to modify the ajax Post data in a beforeSend event?

Hello I have a form that submits remotely with the jQuery UJS for rails. I binded to the beforeSend event to allow me to modify the data submitting to the serve. It's not working. Here is what I have in the beforeSend:
settings.data = JSON.stringify({
'list_item[title]' : 'hi?? there'
})
This doesn't work. In the server logs I see this:
Started POST "/lists/9/list_items" for 127.0.0.1 at 2011-10-24 14:04:36 -0700
Processing by ListItemsController#create as JSON
Parameters: {"{\"list_item"=>{"title"=>{"\":\"hi?? there\"}"=>nil}}, "list_id"=>"9"}
Any idea what I'm doing wrong? I want to customize the settings.data with added fields that aren't in the form. Thanks
You don't need to stringify anything to put it in settings.data. The data is:
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. [...] Object must be Key/Value pairs.
What you're doing is putting this string:
"{"list_item[title]":"hi?? there"}"
into data but that string is not a query string so things are going to get confused. You should be able to simply assign your JavaScript object to settings.data:
settings.data = { 'list_item[title]' : 'hi?? there' };
and let jQuery sort it out from there.
Update based on evidence rather than documentation:
However, further investigation reveals that this doesn't work. If I send a GET request, any changes I make to settings.data are ignored but if I send a POST request, then changes to settings.data stick but you have to use the query string format to get anything sensible through:
settings.data = encodeURIComponent('list_item[title]')
+ '='
+ encodeURIComponent('hi?? there');
The version of settings.data combined with a POST request gets me this:
Parameters: {"list_item"=>{"title"=>"hi?? there"}}
on the server and that looks like what you're after. If you want to preserve some of the original parameters then you'll have to unpack and repack the query string by hand.

Return String from Cross-domain AJAX Request

I'm looking for a way to return a single JSON/JSONP string from a cross-domain "AJAX" request. Rather than request the string and have JQuery return it as a generic object automatically, I want to get a hold of the string BEFORE that conversion happens. The goal here is to parse it myself so I can turn it straight into new objects of a certain type (e.g. a Person object).
So, just to make this clear, I don't want any string-to-generic-object conversion going on behind the scenes and this must work using a different domain.
Here's a non-working example of what I would like to do:
$.ajax({
type: 'GET',
url: 'http://www.someOtherDomain.com/GetPerson',
dataType: 'text',
success: parseToPerson
});
function parseToPerson( textToParse ) {
// I think I can do this part, I just want to get it working up to this point
}
I'm perfectly happy if JQuery isn't involved in the solution, as long as it works. I would prefer to use JQuery, though. From what I've read, the javascript techniques used to get JSONP data (dynamically creating a script element) would probably work, but I can't seem to get that to work for me. I control the domain that I am requesting data from and I can get the data if I change the dataType in the AJAX call to 'JSONP', so I know that is working.
If your data is being retrieved from another domain, you will need to use JSONP (there are other options, but JSONP is by far the easiest if you control the service). The jQuery call will look like this:
$.ajax({
// type: 'GET', --> this is the default, you don't need this line
url: 'http://www.someOtherDomain.com/GetPerson',
dataType: 'jsonp',
success: parseToPerson
});
The actual request that goes to your service will be http://www.someOtherDomain.com/GetPerson?callback=arbitrary_function_name. On the service side, you will need to return data like this:
arbitrary_function_name("the string (or JSON data) that I want to return");
So you'll need to inspect the querystring parameters, get the value of the callback parameter, and echo it out as if you're calling a Javascript function with that name (which you are), passing in the value you want to provide through the service. Your success function will then get called with the data your service provided.
If you're deserializing the returned data into a Javascript object, you might be better off returning JSON data than a string, so the data your service returns might look like this:
arbitrary_function_name({
"name":"Bob Person",
"age":27,
"etc":"More data"
});
That way you don't have to worry about parsing the string - it'll already be in a Javascript object that's easy to use to initialize your object.
Not sure how this will work in conjuction with jsonp, but maybe converters is what you're looking for?
$.ajax(url, {
dataType: "person",
converters: {
"text person": function(textValue) {
return parseToPerson(textValue);
}
}
});

Categories