This question already has answers here:
How to get POSTed JSON in Flask?
(13 answers)
Closed 6 years ago.
I've got a google-maps lookup with autocomplete on the client side - I'm trying to transfer the "place" object over to the server once the user selects it - I could parse it down client-side, but I figured it's easier to do server-side. I verified from the browser 'network' inspect that it is sending over the correct json object, but server side I can't get the right object. I've tried every permutation of request.* that I can find and either get None or a <module 'flask.json'> which I know isn't right.
Code:
function sendplace() {
$('placebutton').click(function() {
var add1 = place;
console.log(place);
$.ajax({
url: '/new_place2',
data: JSON.stringify(place),
contentType: 'application/json;charset=UTF-8',
type: 'POST',
success: function(response) {
console.log(response);
},
error: function(error) {
console.log(error);
}
and server-side:
#app.route('/new_place2', methods=['GET', 'POST'])
def new_place2():
place = request.form.get('place')
print "address: ", place
return ("Success, (*&)er!")
You should use request.get_json(). request.form is reserved for the mimetype application/www-form-urlencoded. If get_json() doesn't work look at request.data and ensure that you can run the following on it:
import json
data = json.loads(request.data)
data.get('place')
If that doesn't work you probably have a problem with your JSON
Related
There is a python server that receives a GET request with a file_id and it triggers downloading that file from another website to a local directory at the python server side. This is done by ajax request in popup.js. I can get the percentage of the downloading file and I can log it continuously in the console. Problem is that I want to show that status as a downloading bar in the popup.html. Is there a way to continuously listen on a event after request like socket.io? I really stuck thinking about how to implement that.
python server
app = Flask(__name__)
#app.route("/<file_id>", methods = ['GET'])
def main(course_id):
// trigger the file downloader this is running asynchronously and
// logs the amount of downloading
response = jsonify({'message': file_id + ' will be downloaded!!'})
response.headers.add('Access-Control-Allow-Origin', '*')
return response
popup.js
$(function(){
$('#download_button').click(function(){
chrome.storage.sync.get(['fileID'], function(result) {
$.ajax({
type: 'GET',
url: "http://localhost:80/"+result.fileID,
crossDomain: true,
success: function(response) {
alert("success: "+response.message);
// here I need to start showing the status of the downloading file
},
error: function (err) {
alert("error");
}
});
})
});
});
Please help me to design this use case, Thanks in advance!!
I'm answering my own problem. I got this resolved by generating urls for the files and send them as the respond to the jQuery request. Then downloading status of each file could be handled independently without much of struggle.
I'm processing a table of banking/statement entries that have been exported from another system via a CSV file. They are imported into a view and checked for duplicates before being presented to the user in a HTML table for final review.
Once checked they are sent via AJAX to the server so they can be added into a Django model. Everything is working OK including CSRF but I cannot access the POSTed variable although I can see it!
Unfortunately making a hidden form isn't viable as there are 80+ rows to process.
My Javascript looks like:
$.ajax({
type: 'POST',
url: '......./ajax/handleImports/',
data: entriesObj,
success: function (data) {
if (data.response && data.response) {
console.log("Update was successful");
console.log(data.entries)
} else { ... }
},
error: function() { ... }
where entriesObj is
var entriesObj = JSON.stringify({ "newentries": newEntries });
console.log(entriesObj)
and when dumped to console.log looks like:
{"newentries":[{"Include":"","Upload ID":"0","Date":"2019-01-09", ... }
Now in view.py when I return the whole request.POST object as data.entries using
context['entries'] = request.POST
return JsonResponse(context)
I get
{"{"newentries":[{"Include":"","Upload ID":"0","Date":"2019-01-09", ... }
but if I try and retrieve newentries with:
entries = request.POST.get('newentries', None)
context['entries'] = entries
return JsonResponse(context)
the console.log(data.entries) will output null?
How am I supposed to access the POSTed entriesObj?
The data is JSON, you need to get the value from request.body and parse it.
data = json.loads(request.body)
entries = data.get('newentries')
I'm trying to create an order using JS. I've authenticated my app and have a function that POST's to orders.json. I see a status code of 200, indicating that the request submitted OK (right?) but the order itself never gets created. I've heard something about disabling cookies in my request, but I don't know how to do that, so if that's what I need to do please let me know.
I'm putting up my entire function, since I'm new to this entire thing and it seems that it's probably the structure of my request, not the API call. I'm seeing the "Error" log in the console, so clearly the error function is running.
function submitShuffle(prodid)
{
console.log(prodid);
var params = {
"order": {
"line_items": [
{
"variant_id": prodid,
"quantity": 1
}
]
}
};
$.ajax({
type: 'POST',
url: 'https://<my-usrnam>:<my-pass>#toyboxshufflesandbox.myshopify.com/admin/orders.json',
dataType: 'application/json',
data: params,
success: function(data){
console.log(data);
},
error: function(data){
console.log("Error");
console.log(data);}
});
}
You cannot retrieve information from Shopify Admin API by AJAX. There is a limitation about this because you have to expose your username/key and password which is not a good idea.
You have to use some service/app or just to create a custom app.
Shopify returns an Object when you make a call. Hence 200 OK status. Inspect the object returned. A failed create POST object will not have an ID. So there is clue number one. Secondly, you'll see that Shopify tells you what the problem was in the Error key of the returned object. If you cannot figure out what you did with the message from Shopify, make the same call to the GraphQL endpoint if you can, as the error messages Shopify returns from those endpoints are currently much better. They are backporting them to the older REST API, but for now, GraphQL is more expressive.
I got a very strange problem, I thought this worked before but it doesn't any more. I dont even remember changing anything. I tried with an older jQuery library.
I got an error that says: http://i.imgur.com/H51wG4G.png on row 68: (anonymous function). which refer to row 68:
var jsondata = $.parseJSON(data);
This is my ajax function
I can't get my alert to work either because of this error. this script by the way is for logging in, so if I refresh my website I will be logged in, so that work. I also return my json object good as you can see in the image. {"success":false,"msg":"Fel anv\u00e4ndarnamn eller l\u00f6senord.","redirect":""}
When I got this, I will check in login.success if I got success == true and get the login panel from logged-in.php.
$('#login_form').submit(function()
{
var login = $.ajax(
{
url: '/dev/ajax/trylogin.php',
data: $(this).serialize(),
type: 'POST',
}, 'json');
login.success(function(data)
{
var jsondata = $.parseJSON(data);
console.log(jsondata);
if(jsondata.success == true)
{
$.get("/dev/class/UI/logged-in.php", function(data) {
$(".login-form").replaceWith(data);
});
}
else
{
alert(jsondata.msg);
$('#pwd').val('');
}
});
return false;
});
Thank you.
If the response you have showed in the attached screenshot is something to go by, you have a problem in your PHP script that's generating the JSON response. Make sure that thePHP script that's generating this response (or any other script included in that file) is not using a constant named SITE_TITLE. If any of those PHP files need to use that constant, make sure that that SITE_TILE is defined somewhere and included in those files.
What might have happened is that one of the PHP files involved in the JSON response generation might have changed somehow and started using the SITE_TITLE costant without defining it first, or without including the file that contains that constant.
Or, maybe none of the files involved in the JSON generation have changed, but rather, your error_reporting settings might have changed and now that PHP interpreter is outputting the notice level texts when it sees some undefined constant.
Solving the problem
If the SITE_TITLE constant is undefined, define it.
If the SITE_TITLE constant is defined in some other file, include that file in the PHP script that's generating the response.
Otherwise, and I am not recommending this, set up your error_reporting settings to ignore the Notice.
Your response is not a valid JSON. You see: "unexpected token <".
It means that your response contains an unexpected "<" and it cannot be converted into JSON format.
Put a console.log(data) before converting it into JSON.
You shoud use login.done() , not login.success() :)
Success is used inside the ajax() funciton only! The success object function is deprecated, you can set success only as Ajax() param!
And there is no need to Parse the data because its in Json format already!
jQuery Ajax
$('#login_form').submit(function()
{
var login = $.ajax(
{
url: '/dev/ajax/trylogin.php',
data: $(this).serialize(),
type: 'POST',
}, 'json');
login.done(function(data)
{
var jsondata = data;
console.log(jsondata);
if(jsondata.success == true)
{
$.get("/dev/class/UI/logged-in.php", function(data) {
$(".login-form").replaceWith(data);
});
}
else
{
alert(jsondata.msg);
$('#pwd').val('');
}
});
return false;
});
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
django file upload from json
Hi am using the following ajax upload from the template but i do not get a response from django view.What is wrong here..i do not see any alert
function ajax_upload(formid)
{
var form = $(formid);
form.ajaxSubmit({
dataType: 'json',
success: function (data) {
alert("Hereeeeeeee");
if(data.status == '1')
{
alert("Uploaded Successfull");
}
else
{
alert("Uploaded UnSuccessfull :(");
}
}
} ) ;
}
EDIT
Django:
def someview(request):
response_dict={'status':1}
logging.debug("seen") //This is seen in the logs
return HttpResponse(simplejson.dumps(response_dict), mimetype='application/javascript')
EDIT1
Please also for complete source code look at django file upload from json
From your code:
form.ajaxSubmit({
dataType: 'json',
success: function (data) {
alert("Hereeeeeeee");
Your callback executes on 'success', so we can narrow down the failure to the django view side. Assuming everything is syntactically correct, my best guess is that since you're returning json data, your response mimetype should be:
mimetype='application/json'.
If that doesn't work, I would suggest using Firebug on Firefox or Developer Tools on Chrome to look at the server response. You should be able to see a django stacktrace there.
Check that someview added to urls.py.
Check that {% csrf_token %} added to form
It's rather impossible you will see that log, hence this is a python syntax error:
response_dict{'status':1}
and should be:
response_dict = dict(status=1)
or:
response_dict = {'status':1}
or:
response_dict = dict()
response_dict['status'] = 1
or:
response_dict = dict()
response_dict.update({'status':1})