post data from ember js to python - python-2.7

iam using ember js with python and tornado server.
I want to send the json data from ember js to python.
here is what i have tried
App.MyleavesController = Ember.ObjectController.extend({
submitAction: function () {
data=[{fromdate:this.get("model.fromdate")}]
$.ajax({
type: "POST",
url: "/apply_leave",
data: JSON.stringify(data),
success: function ( data ) {
}
});
}
});
in my python it is
class LeaveFormHandler(tornado.web.RequestHandler):
def post(self):
print json.loads(data)
but i could not get data..
it says " global name 'data' is not defined"
am a newbie please help..

For a POST request, use json.loads(self.request.body). Arguments to post() are extracted from the url regex.

Related

Unexpected token P in JSON at position 0 when trying to return Excel spreadhsheet

I have an emberJS application where I can make a POST AJAX call to a Django backend. A function in Django creates an xlsx file for a bunch of queried items based on IDs coming in the POST request. It goes through the Django view function without any issues, but when the HTTP response is returned to ember, I get the error
SyntaxError: Unexpected token P in JSON at position 0
at parse (<anonymous>)
at ajaxConvert (jquery.js:8787)
at done (jquery.js:9255)
at XMLHttpRequest.<anonymous> (jquery.js:9548)
at XMLHttpRequest.nrWrapper (base-content:20)
I'm setting the response content type to application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, so I'm unsure as to why its trying to read the response as JSON.
Python Code
file_path = '/User/path_to_spreadsheet/content.xlsx'
fsock = open(file_path, "rb")
response = HttpResponse(fsock, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = 'attachment; filename="content.xlsx"'
return response
EmberJS Code
export default Controller.extend({
actions: {
storeProductId(products) {
let product_ids = []
products.forEach(function(product){
product_ids.push(product.id)
});
let adapter = this.store.adapterFor('product-export');
adapter.export_products(product_ids).then(function(response){
console.log(response)
}).catch(function(response) {
console.log('ERROR')
console.log(response)
})
}
}
});
Product-Export Adapter Code
export default ApplicationAdapter.extend(FormDataAdapterMixin, {
export_products(products) {
let url = this.buildURL('unified-product');
url = `${url}export/`;
return this.ajax(url, 'POST', { data: {'products': products} });
}
});
By default, Ember Data makes some assumptions around how things should be handled (including that you’ll be receiving JSON data back). Is there a reason you are using Ember Data instead of using a direct Ajax call to your backend? Seems like that would greatly simplify things here ...

flask endpoint for ajax call

I'm making an ajax call to my server while pressing submit button.
Button is present in page http://127.0.0.1:5000/post/15.
Jquery function invoked and the endpoint definition for submit_comment in python respectively:
function submit_comment(post_id) {
var uname = $('input[name="uname"]').val();
var comment = $('textarea[name="comment"]').val();
$.ajax({
url: "/submit_comment",
data: {name: uname, comment: comment, post_id: post_id},
method: "POST",
datatype: 'json',
success: function(response) {
console.log('reaches here');
addElement(response);
console.log('Is it me');
},
error: function(error) {
console.log('reached Error');
console.log(error);
}
});
}
py
#main.route('/submit_comment', methods = ['POST', 'PUT'])
def submit_comment():
entry = request.get_json(force=True)
print 'comment:', entry
....
Main is the blueprint. But I'm getting following 404 error.
127.0.0.1 - - [24/Aug/2017 10:30:55] "POST /post/submit_comment HTTP/1.1" 404 -
I am wondering from where this post got appended into the endpoint.
Can someone help me to understand the error and resolve it?
Thanks,
Deepak
I don't know a lot, but I know that the Flask docs on ajax say to query for the script root like this:
$SCRIPT_ROOT = {{ request.script_root|tojson }};
and then use that as part of the request URL.
An example from an ajax call I've used ($.getJSON being a jquery function for $.ajax)
$.getJSON($SCRIPT_ROOT + '{{ url_for("help_email") }}',

Fetch API for Django POST requests

I'm trying to remove jQuery from a React/Redux/Django webapp and replace the $.ajax method with the Fetch API. I've more or less got all my GET requests working fine and I seem to be able to hit my POST requests, but I cannot seem to format my request in such a way as to actually get my POST data into the Django request.POST object. Every time I hit my /sign_in view, the request.POST object is empty. My entire app's backend is built around using Django forms (no Django templates, just React controlled components) and I would really like to not have to rewrite all my views to use request.body or request.data.
Here is all the code I can think that would be relevant, please let me know if there's more that would be helpful:
This is the curried function I use to build my full POST data and attach the CSRF token:
const setUpCsrfToken = () => {
const csrftoken = Cookies.get('csrftoken')
return function post (url, options) {
const defaults = {
'method': 'POST',
'credentials': 'include',
'headers': {
'X-CSRFToken': csrftoken,
'Content-Type': 'application/x-www-form-urlencoded'
}
}
const merged = merge(options, defaults)
return fetch(url, merged)
}
}
export const post = setUpCsrfToken()
This is the API method I use from my React app:
export const signIn = data => {
return post('/api/account/sign_in/', data)
}
The data when it is originally packaged up in the React app itself is as simple as an object with string values:
{
email: 'email#email.com',
password: 'password
}
I've looked at these questions and found them to be nominally helpful, but I can't figure out to synthesize an answer for myself that takes into account what I assume is some of the intricacies of Django:
POST Request with Fetch API?
Change a jquery ajax POST request into a fetch api POST
Convert JavaScript object into URI-encoded string
Is there a better way to convert a JSON packet into a query string?
Thanks!
You have to set the appropriate X-Requested-With header. jQuery does this under the hood.
X-Requested-With: XMLHttpRequest
So, in your example, you would want something like:
const setUpCsrfToken = () => {
const csrftoken = Cookies.get('csrftoken')
return function post (url, options) {
const defaults = {
'method': 'POST',
'credentials': 'include',
'headers': new Headers({
'X-CSRFToken': csrftoken,
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'X-Requested-With': 'XMLHttpRequest'
})
}
const merged = merge(options, defaults)
return fetch(url, merged)
}
}

Using ember data to save multiple records via post

Does anyone know of any working examples of overriding ember-data's DS.Adapter to save all records at once?
I'd like to stringify my entire array of records and send them to my server. I don't have much flexibility on the server to use anything but the existing API which is just a perl CGI script. Any help in the right direction would be appreciated.
What I did was iterate over the ember-data models, serialized them, saved them into a json object that matched server requirements, and executed post request.
var identifiedResponse = []
this.store.filter(key, function (record) {
return !!record.get('name')
}).then(function(resp) {
identifiedResponse.push(item.serialize())
})
jQuery.ajax({
url: url,
type: "POST",
data: identifiedResponse,
contentType: "application/json",
dataType: 'json',
xhrFields: {
withCredentials: true
}
})

Why does my Django request.method does not match POST

$.ajax({
type :'GET',
url : geturl(a),
// type: $(this).attr('method'),
dataType : 'json',
views.py:
if request.method=="POST":
if request.POST.get('monyrsubmit'):
monthform=MonthForm(request.POST)
if monthform.is_valid():
selected_month=monthform.cleaned_data["Month"]
selected_year=monthform.cleaned_data["Year"]
print selected_month
print selected_year
can i have both GET and POST requests in the type field of ajax. im using a form and only when the submit button is clicked im trying to display information based on the data submitted. if request.POST.get('monyrsubmit') does not work.
Help will be appreciated
It's very simple. You have to abstract the events.
function event_page_load() {
function ajax_request('GET')
}
function click_submit_button() {
function ajax_request('POST')
}
function ajax_request(type) {
$.ajax({
type : type,
......
......
})
}
You can also consider the follwoign general guidelines.
GET and POST should be used based on the type of the request to the server
- If you are reading the existing data(without modification) from the server, use GET
- if you are writing/modifying any data in the server, use POST
in jQuery, you can use these simple methods.
For GET requests
$.get(
url,
{param1: "value1", param2: "value2"},
function(responseText){
// todo ;
},
"html"
);
for POST requests
$.post(
url,
{param1: "value1", param2: "value2"},
function(responseText){
// todo ;
},
"html"
);
Make sure that you have disable the browser caching.
$.ajaxSetup ({
cache: false
});
In django side, you can use request.is_ajax() method to verify the ajax call and you can filter based on request.method property.
You can refer all the possible usages of AJAX with Djano at https://github.com/sivaa/django-jquery-ajax-exmaples