Execute a python function without response - Django [duplicate] - javascript

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...

Related

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

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|}

Can someone explain me how to do a JSONP call like I'm five? [duplicate]

This question already has answers here:
What are the differences between JSON and JSONP?
(8 answers)
Closed 9 years ago.
I already have a .json object in a server. It is correct and has no syntax errors (valid json). I want to call this object through JSONP because it resides in a server different from my app's.
I think I understand how to achieve it client-wise, but I have no idea what to do in relation to the server part. I am having errors all the time when following the info already on the web. Any help?
JSONP is basically a "hack" to allow sites to load data and ignore the same-origin policy. It works by appending a <script> tag to your page.
The de facto way is to send a callback in your request. The server would then take that name and generate a JS file that calls that function with the data.
Using jQuery, you can make a JSONP call by simply appending ?callback=? to your URL when doing $.getJSON.
Example:
$.getJSON('http://YourSite.com/path/to/json.php?callback=?', function(data){
console.log(data); // this will be parsed for you
});
Or, you can use the full $.ajax method:
$.ajax({
url: 'http://YourSite.com/path/to/json.php',
dataType: 'jsonp', // this tells jQuery to add "callback=?" for you
success: function(data){
console.log(data); // this will be parsed for you
}
});
Instead of makning an AJAX call, jQuery will actually append:
<script src="http://YourSite.com/path/to/json.php?callback=jQuery12345"></script>
to your page (note: jQuery12345 will be randomly generated).
Then on your server, you need to respond with a valid JavaScript file. It should contain a call to the callback function passed in the query string. Something like this:
jQuery12345({your: ['json', 'data']});
An example in PHP (adapt to whatever server-side language you use) could be:
$array = ['a' => 1, 'b' => 2,'c' => 3];
$callback = $_GET['callback'];
header('Content-type: text/javascript');
echo "{$callback}(".json_encode($array).");";
That's all there is to it. See the Wikipedia page on JSONP for more info: http://en.wikipedia.org/wiki/JSONP
JSONP has nothing to do with JSON. Here's a simple (but useless) example:
The client makes a script element: <script src="http://example.com/foo.js>. This causes the browser to fetch foo.js from example.com.
The server hears the request for foo.js. The server serves the contents of foo.js to the client (suppose it's just alert(1)).
The client gets the contents of foo.js and runs those contents as a script. (So, the client does alert(1).)
How is this useful? Well, you can pass arguments with your request to foo.js:
The client does <script src="http://example.com/foo.js?arg=123>
The server hears a request for foo.js?arg=123. The server does something with that arg value -- let's suppose it multiplies it by 2 (but it could do something useful, like look up the username for the user with uid 123). The server then sends back the script content alert(246).
**The client runs the script from the server and alerts 246.
Okay, this is great if I want the client to alert stuff, but how can I do something useful? There's just one last leap we have to make: provide the name of a client function as an argument:
The client defines a function myFunc as: function myFunc(a) { alert(a) }
The client does <script src="http://example.com/foo.js?callback=myFunc&arg=123>
The server hears the request for foo.js?callback=myFunc&arg=123, and its server-side scripting knows it should use the callback argument as the name of the function called in foo.js. The server sends back the script content myFunc(246).
The client runs myFunc(246). Here, we've specified myFunc to just alert its argument, but you could have it do anything you like.
That's how JSONP works. The client provides arguments to the server in a script URL, including the name of a client-side function, and the server sends back a script (not JSON!) for the client to run. Of course, the resulting script can contain JSON in it, like myFunc({ 'foo' : 5 }), but ultimately, that JSON is just part of the script content.

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'))
});

JSON.parse works but jQuery.getJSON returns http error 403

When I use JSON.parse(jsonString), the JSON is parsed no problem at all.
var result = JSON.parse(jsonString);
But when I use jQuery.getJSON(jsonString) i received an http error 403.
var result = jQuery.getJSON(jsonString);
Any idea why one will work and the other will not? They are both reading a string.
Thanks!
They are both reading a string.
Oh no! Those two methods are so very much different. They have absolutely nothing in common. They are accomplishing 2 entirely different tasks.
The first simply parses a JSON string into a javascript object:
var result = JSON.parse('{"foo": "bar"}');
alert(result.foo);
will show bar. Also notice that the JSON.parse method is a built-in method in modern browsers. It's pure javascript and has strictly nothing to do with jQuery. Legacy browsers do not support it. For them you need to include the json2.js script to your page.
The second performs an AJAX call and expects as argument an url:
jQuery.getJSON('/someserversidescript', function(result) {
// callback to be executed when the AJAX request succeeds
});
As you can see here the argument is an url. Calling jQuery.getJSON('{"foo": "bar"}') makes strictly no sense. I guess that's the reason why your server responds with 403 error, since this is not valid url on your server. It expects that the server will return a JSON string as response. It's simply a shorthand for:
$.ajax({
url: '/someserversidescript',
type: 'GET',
dataType: 'json',
success: function(result) {
// callback to be executed when the AJAX request succeeds
}
});
getJSON() is an asynchronous call back to a server that returns a JSON object. JSON.parse() takes a string and returns a JSON object in memory. They are completely different.

ajax request returning script tag-- mootools

I'm seeing a weird error in one of my ajax-updated pages.
The request looks like this:
var a = new Ajax(url,{
method: 'get',
onComplete: function( response ){
$('loader').style.display="none";
readData( response );
}
});
a.request();
return;
This works fine on almost any system so far, but on a new server it breaks, with a mootools error "unknown XML entity". The weird part is, if you trace the request with firebug, rather than returning JSON as expected, the response body looks like this:
<script>document.location.href='http://www.mysite.com?myparams=value&etc;</script>
However, if you actually make that request manually by pasting the URL in the script tag (response body) along with the params in a browser, the proper JSON data is returned.
Any ideas why the request would return a script tag instead of the data?
As Dimitar suggested in the comments above, this was an issue in a Joomla site thanks to a URL rewrite tool called sh404SEF. According to the developer, the fix is to set the "301 redirect" parameter to "no" in the advanced configuration options.
So this had nothing to do with my code or the ajax functions, but was rather the SEF rewrite component that was breaking the request.

Categories