I am working on a flask app and I am sending this ajax request to '/repl' endpoint
$.ajax({
type: "GET",
url : "/repl?code=",
data: "print \"hello\"",
contentType: 'application/json;charset=UTF-8',
success: function(result){
alert(result.output);
}
});
and code of my controller i.e. view.py is
#app.route('/repl', methods=['GET'])
#app.route('/repl/', methods=['GET'])
def execute():
code = request.args.get("code", None)
print code
# execute python code in sandbox
out, err = exec_sandbox(str(code))
return jsonify(success=1, output=out, error=err)
but it is not working. Code variable always receives None value. Please help
after running app, this request builds up
127.0.0.1 - - [28/Mar/2014 03:59:59] "GET /repl/?code=&print%20%22hello%22 HTTP/1.1" 200
change ajax code to :
$.ajax({
type: "GET",
url : "/repl",
data: {url : "print \"hello\""},
contentType: 'application/json;charset=UTF-8',
success: function(result){
alert(result.output);
}
});
Related
I am not able to retrieve data field of AJAX in python flask.
Its shows type error when I try to retrieve data. type and forwho are of array type. When I alert them in AJAX it works.
Here is my code,
// Ajax
$.ajax({
url: '/products',
data: JSON.stringify({'type':type,'forwho': forwho}),
contentType: "application/json; charset=utf-8",
type: 'POST',
success: function(response){
/*alert("success");*/
$("#content").html(response);
},
error: function(error){
/*alert("error");*/
console.log(error);
}
});
# app.py
#app.route('/products', methods =['POST', 'GET'])
def all_products():
if request.method == 'POST':
print("inside all products post")
type = json.loads(request.form.get('type'))
forwho = json.loads(request.form.getlist('forwho'))
print(type)
print(forwho)
when I print print(request.args.get('typearr')) in all_products() it returns None
type =request.json['type']
forwho = request.json['forwho']
Flask automatically parses JSON when having application/JSON in your request.
This solution finally worked for me.
ajax:
data: JSON.stringify({'typearr':type,'forwho':forwho})
``````````````````
app.py:
#import ast
``````````````
data = request.get_data()
data = ast.literal_eval(data.decode("UTF-8"))
typearr = data['typearr']
forwho = data['forwho']
I was trying to get some information from API using ajax. I was able to post data but I was unable to get all the data from the server. I am new in the Django environment, though i have tried some references. I was wanted to get the data from the server using the API that I provide and show those data by using ajax get call.
References that I have followed:
1.Django Ajax Jquery Call
2.https://simpleisbetterthancomplex.com/tutorial/2016/11/15/how-to-implement-a-crud-using-ajax-and-json.html
3.https://www.sourcecodester.com/tutorials/python/11762/python-django-simple-crud-ajax.html
My code for get call:
$.ajax({
type: "GET",
url: "/save_composition",
dataType: "json",
success: function(data) {
alert(data)
},
error: function(xhr, textStatus) {
alert("error..");
}});
Url section :
path('restore_composition/', views.restore_composition, name='restore_composition')
Views.py:
def restore_composition(request):
data = SaveComposition.objects.all()
return render(request, 'index.html', context={'data': data})
This is how ajax calls works in Django framework.
def ajax_method():
return HttpResponse(200)
url to the ajax call
path('save_composition', views.ajax_method, name='ajax_method')
You need to set the `url-path' without forward-slash
Ajax call
$.ajax({
type: "GET",
url: "save_composition",
dataType: "json",
success: function(data) {
alert(data)
},
error: function(xhr, textStatus) {
alert("error..");
}});
This question already has answers here:
jQuery posting JSON
(3 answers)
Closed 6 years ago.
I want to use jQuery to send JSON data to a Flask route. However, request.get_json() gives an error. Why doesn't this work?
my_array = {"student_data":{"actual_data":12,"sheet_data":23,"age":"20"},"teacher_data":{"actual_data":193,"sheet_data":203,"age":"40"},"school_data":{"actual_data":593,"sheet_data":29,"age":"49"}};
$.ajax({
url: '/submit_method',
data: my_array,
contentType: 'application/json; charset=utf-8',
type : 'GET',
async: 'false',
success: function (serverResponse) {
}
});
#app.route('/submit_method', methods=['GET'])
def submit_method():
k = request.get_json()
return ''
You have to use POST method instead of GET.
#app.route('/submit_method', methods=['POST'])
def submit_method():
k = request.data # gets request body in form of dictionary
return json.dumps(k) # converts dictionary to json
$.ajax({
url: '/submit_method', data: JSON.stringify(my_array),
contentType:"application/json; charset=utf-8",
type : 'POST', async: "false", success : function (serverResponse) {}});
The issue is JavaScript has to be converted to a JSON string first, using JSON.stringify. Otherwise Flask will not consider it application/json content type and deny the request with a 400.
$.ajax({
url: '/submit_method',
data: JSON.stringify(my_array),
contentType: 'application/json; charset=utf-8',
type : 'GET',
async: 'false',
success: function (serverResponse) {
}
});
I'm new to web2py, trying to alter an existing application.
I have a JSON object in my JS, which I want to send to the server.
My JS is:
post_data = {ios: [{k:"v"},
{k: "v"},
{k: "v"}]};
$.post("/url", post_data, function(data) {}, "json"); // used with 'json' and without, same results
I want to access this data in my controller. so there, I tried to use request.vars.ios and request.post_vars.ios, getting a None ...
What am I doing wrong?
(note: the data is transmitted, and if i try to dump the request.vars, I get something like
<Storage {'ios[1][ranges_colors]': '', 'ios[0] .... etc which contains the data)
Try this, on the client:
$.ajax({
type: 'POST',
url: '/url.json',
contentType: "application/json; charset=utf-8",
data: post_data,
dataType: 'json',
success: function(data) { alert('Data sent'); }
});
Then on the server:
data = gluon.contrib.simplejson.loads(request.body.read())
I am trying to send a request to call a python method in my python script.
Server Side:
I am using flask ,so the server is running on port 5000.It has a file called helloflask.py which look like
#helloflas.py
from flask import Flask
app = Flask(__name__)
#app.route("/hello",methods=['GET','POST'])
def hello():
return "Comming Here"
if __name__ == "__main__":
app.run(port=5000,debug=True)
Client Side:
Independent HTML outside of flask which is sending the ajax request.
<!--ajax call-->
<script>
function findAppartment() {
$.ajax({
url: "https://127.0.0.1:5000/hello/",
type: "get",
contentType: "application/xml; charset=utf-8",
success: function (response) {
// $('#blurg').html(response).fadeIn(1500);
}
});
}
</script>
when the request is made,I get the following error.It hits the server and gives the following error:
Error : code 400, message Bad request syntax ('\x16\x03\x01\x00\xa1\x01\x00\x00\x9d\x03\x02Q\xd8\xc0O+\x8f\xa6\x16F\x9a\x94\x90|$\x11\xd3\xd8\x15\x04$\xe4\xb4>\xc0\x0e\xe3\xa0h\xea\x07\x00\xc5\x00\x00H\xc0')
I tried many things but things don't seem to be working.Could any one help???Any help is highly appreciated.