Sending a dictionary from JS to Flask via AJAX [duplicate] - javascript

This question already has answers here:
How do I POST an array of objects with $.ajax (jQuery or Zepto)
(5 answers)
Closed 3 years ago.
I'm trying to send data in a dictionary format from the client side JavaScript to the server back end via AJAX. It is working, however the data received on the Python end is not what I expected.
>>> b'new+class=some_valaue&document+id=1234567'
What I am expecting back is:
{'new class': 'some_value', 'document id': 1234567}
My javascript
$.ajax({
url: '/reclassify',
data: {'new class': 'some_value',
'document id': 1234567,},
type: 'POST',
success: function(response){
console.log(response);
},
error: function(error){
console.log(error);
}
});
My Python/Flask
#app.route('/reclassify', methods=['POST'])
def reclassify():
data = request.get_data()
print(data)
return 'success'
I don't have any if POST statements yet because I'm still trying to figure out how to get the data sent across in the right format.

Python
#app.route('/reclassify', methods=['POST'])
def reclassify():
if request.method == 'POST':
data = request.get_json()
print(data)
return '', 200
JS
function updateClassifier(e, id) {
let newClassData = {
'new class': 'some_value',
'document id': 1234567,
}
$.ajax({
url: '/reclassify',
contentType: "application/json;charset=utf-8",
data: JSON.stringify({newClassData}),
dataType: "json",
type: 'POST',
success: function(response){
console.log(response);
},
error: function(error){
console.log(error);
}
});
}
Output in python
{'newClassData': {'new class': 'some_value', 'document id': '1234567'}}

Related

How to solve JSONdecode error in ajax django?

I'm receiving JSONdecode error when sending the POST request from ajax to django views.py. The POST sends an array of json. The data from this POST will be used to create the model. Appreciate for any hints.
Error:
Exception Type: JSONDecodeError at /order-confirmation
Exception Value: Expecting value: line 1 column 1 (char 0)
Request information:
USER: ledi12
GET: No GET data
POST: No POST data
FILES: No FILES data
AJAX Request:
var new_array = JSON.stringify(array)
$.ajax({
url: 'http://localhost:8000/order-confirmation',
type: 'POST',
data: '{"array":"' + new_array+'"}',
processData: false,
contentType: "application/json",
dataType: "json",
headers: {"X-CSRFToken":'{{ csrf_token }}'},
success: function (result) {
console.log(result.d);
},
error: function (result) {
console.log(result);
}
});
Views:
#csrf_exempt
def order_confirmation(request):
if request.method == 'POST':
data = json.loads(r"request.body").read()
print(data)
return HttpResponse(status=200)
else:
return render(request, 'main_templates/order_confirmation.html')
The reason you are getting this error is because the JSON library is not able to properly compile the string. There are a couple of things that your code needs to change. Remove 'r' character which is near request.body(). There is no need for 'read()' function in json.loads(). You can preprocess your array into a string and once done, and pass it to ajax. The data field will only have the string. So the ajax code field should look like
data: new_array

js to flask and back to js in a single page app

For my single page web app, I need to:
Send a json from .js to flask (DONE)
Run the input through a python function - getString() and get a str output (DONE)
Send the str output back to the .js file (PROBLEM)
Here is the flask app:
#app.route('/',methods =['GET','POST'])
def index():
req = json.dumps(request.get_json())
if request.method == 'POST':
result = getString(req) #Function outputs a string
return jsonify(result)
else:
print('Not Received')
return render_template('index.html')
if __name__ == '__main__':
app.run()
The problem is that the jsonify(result) is not being sent probably due to the request.method == 'POST' switching to else when jsonify is called. Is there any way to fix my code to send the str output to the .js?
Here is the .js:
//To send info to flask
document.querySelector('#generate').addEventListener('click',function() {
var json_inputs = JSON.stringify(inputs);
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "/",
traditional: "true",
data: json_inputs,
dataType: "json"
});
})
//To receive from Flask
$.ajax({
url: "/",
type: 'GET',
success: function(data) {
console.log(data);
}
});
I think you've misunderstood what GET and POST are, GET is a request that only fetches something from the back end without a message body but a POST can send a body and recieve something.
try this instead:
document.querySelector('#generate').addEventListener('click',function() {
var json_inputs = JSON.stringify(inputs);
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "/",
traditional: "true",
data: json_inputs,
dataType: "json",
success: function(data) {
console.log(data);
}
});
})

Error when using JSON to send Javascript object to Python Flask

I am using ajax to POST a JSON string to Python Flask but get the following error:
Error
This is my JavaScript:
$.ajax({
type: 'POST',
url: window.location.href,
data: JSON.stringify(questionObj0),
dataType: 'json',
contentType: 'application/json; charset=utf-8'
}).done(function(msg) {
console.log(msg);
});
And this is my Python:
#app.route('/test', methods=['GET', 'POST'])
def test():
question = request.get_json()
question1 = json.loads(question)
print (question)
return render_template('test.html')
Using print(question) yields the following output (same output when tested in JavaScript using browsers console):
{'questionNumber': 1, 'question': 'Convert 10110001 to decimal', 'answer': 177, 'userAnswer': 'blank'}
From what I understand, the output should be a string and therefore padded with quotation marks.
Has anyone come across anything similar/know how to fix the issue?
Flask's request.get_json() returns a dict object from the JSON data supplied in the request, so you don't need to call json.loads on it again.
app.py
#app.route('/', methods=['GET'])
def index():
return render_template('index.html')
#app.route('/test', methods=['POST'])
def test():
question = request.get_json()
print(question['question'])
return ''
templates/index.html
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
var questionObj0 = {'questionNumber': 1, 'question': 'Convert 10110001 to decimal', 'answer': 177, 'userAnswer': 'blank'};
console.log(JSON.stringify(questionObj0));
$.ajax({
type: 'POST',
url: '{{ url_for('test') }}',
data: JSON.stringify(questionObj0),
dataType: 'json',
contentType: 'application/json; charset=utf-8'
}).done(function(msg) {
console.log(msg);
});
</script>

jquery-1.10.2.js:8706 POST http://127.0.0.1:5000/%7B%7B%20url_for('app.getData')%20%7D%7D 404 (NOT FOUND)

I want to get json from js to python script as a json and not as a string.
I am getting the above error in chrome browser's console when I write the following:
javascript code:
data.push({
"start":0,
"end":10
});
console.log(JSON.stringify(data));
$.ajax({
type : "POST",
url : "{{ url_for('app.getData') }}",
data: JSON.stringify(data, null, '\t'),
contentType: 'application/json;charset=UTF-8',
success: function(result) {
console.log(result);
}
});
python code:
#app.route('/getData', methods=["GET", "POST"])def getData():
if request.method == "POST":
print(request.json['start'])
return request.json['start']

POST Request in Ruby [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Make this HTTP POST request in ruby
How do you perform the following JavaScript request in Ruby?
url = 'http://www.example.com/';
data 'name=aren&age=22';
$.ajax({
type: "POST",
url: url,
data: data,
dataType: "json",
error: function() {
console.log('error');
},
success: function(data) {
console.log('success');
}
});
Check out HTTParty, great gem https://github.com/jnunemaker/httparty
Example:
response = HTTParty.post(url, body: data)
puts response.body, response.code, response.message, response.headers.inspect
Although I believe it is synchronous- dont quote me on that though

Categories

Resources