Passing HTML data into Flask - javascript

I have a web application from which I want to pass a text box value into a flask application.But, when I print out the request object in flask I do not get the data.Can you kindly help me out.Here are the codes:
Flask Server:
#app.route('/send_data', methods=['GET', 'POST'])
def send_data():
print request
if request.method == "POST":
#Operations with the data received
else:
return jsonify(txt="Nothing received");
HTML CODE:
<div id="div_submit">
<form name="form_submit">
<textarea cols="100" rows="1" id="txt_query">
</textarea>
<br>
<br/>
<input type="submit" value="Submit" onclick="send_query()">
</form>
</div>
Javascript:
function send_query()
{
var qry=document.getElementById("txt_query").value;
//alert(qry);
var contentType = "application/x-www-form-urlencoded";
var ajax=$.ajax({
type: "POST",
url: "http://0.0.0.0:8080/send_data",
data: JSON.stringify(qry),
dataType: "json"
}).done(function(data){
alert("success");
});
ajax.fail(function(data){
alert("fail");
});
}

You are posting JSON data; set the content type to application/json and use the request.get_json() method to load the data:
var ajax=$.ajax({
type: "POST",
url: "http://127.0.0.1:8080/send_data",
data: JSON.stringify({query: qry}),
dataType: "json",
contentType: "application/json; charset=UTF-8"
})
where the URL has to be meaningful; 0.0.0.0 is okay for servers (it means 'bind to all interfaces') but you are probably running this on localhost, so use that to begin with.
In your view use:
data = request.get_json()
query = data['query']

You need to use a request in your flask app to receive the data:
http://flask.pocoo.org/docs/quickstart/#the-request-object

Related

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>

Getting a 405 GET error when using json POST to Flask Server

I am trying to send some data to a Flask app using json. When I send it I get a GET error in the console
GET http://super.secret.url/csv?callback=jQuery...
Javascript:
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: "http://super.secret.url/csv?callback=?",
data: JSON.stringify({message: id, condition: "new"}),
dataType: "json"
});
Flask (python):
#app.route('/csv', methods=['POST'])
#crossdomain(origin='*')
def edit_csv(path):
ip = request.remote_addr
sessionId = request.json['message']
type = request.json['condition']
csvFile = csv.reader(open('ip_log.csv'))
csvLines = [l for l in csvFile]
if(type == "new"):
for i in range(0, len(csvLines)):
if(csvLines[i][0] == ip):
csvLines[i][1] == sessionId
break
csvwriter = csv.writer(open('ip_log.csv', 'w'))
csvwriter.writerows(csvLines)
return ""
Edit
I am getting a 405. I know this is a cross domain request but I do have the server setup to handle that. I have a different function in the python file that works cross domain.
To solve the cross domain problem, you may try JSONP instead of JSON.
For instance, the ajax code gives as follows:
$.ajax({
type: 'POST',
dataType: 'jsonp'
url: "http://super.secret.url/csv?callback=?",
jsonp: 'callback'//to get your own callback function name
jsonpCallback:'youOwnFunction',//'youOwnFunction' is callback function
//success or error function
});
return data shows like that
youOwnFunction({
//return data
});

Why is ajax request submitting 'none' for value of dom element?

I have a simple input box in a form the value of which I'm trying to send to django via Ajax post, but I'm getting a 500 error ValueError at /rest/
Cannot use None as a query value
<form onsubmit="return false;">
{% csrf_token %}
Search:<input type="text" name="artist" id="artist" />
<button class="updateButton" onclick="createlist()">submit</button>
</form>
<script>
function createlist(){
$.ajax({
type: "POST",
url: "/rest/",
dataType: "json",
data: {
csrfmiddlewaretoken: "{{ csrf_token }}",
artist: $('#artist').val()
},
success: function(data){
$('body').append(data.results);
}
});
}
</script>
View:
def rest(request):
artistname = request.POST.get("artist") # <- problem here?
response_data = {}
query_results = Art.objects.filter(artist__contains=artistname)
response_data['results'] = query_results
return HttpResponse(json.dumps(response_data), content_type="application/json")
When I check the headers under Form Data it shows artist: da vinci which is what I typed in. Where is the train getting derailed?
copy, pasted your code and worked for me.
You can try and changing the way you send the POST request.
$.ajax({
type: "POST",
url: "/rest/",
dataType: "json",
data: {artist: $('#artist').val() },
headers: {
'X-CSRFTOKEN': "{{ csrf_token }}",
},
success: function(data){
$('body').append(data.results);
}
});
I figured out the problem. My app/urls.py file was sending the url to the wrong function. I thought the /rest/ url was going to the views.rest function, but for some reason /rest/ was being sent to views.get_search_entry which does something completely different with post requests.
from django.conf.urls import patterns, url
from myapp import views
urlpatterns = patterns('',
url(r'^$', views.get_search_entry, name='get_search_entry'),
url(r'^results/', views.get_search_entry, name='result'),
url(r'^rest/', views.rest, name='rest'),
)
Then I had to serialize the queryset before dumping to json to send over the wire.

Post file using jquery in Django

I want to post a csv file to django view using jquery
<form id="form" enctype="multipart/form-data" >
<input type="file" name="ListFile" id="ListFile" />
<button type="button" onclick="csv_send">upload</button>
</form><br>
js is:
function csv_send(){
var data = {
'csrfmiddlewaretoken' : $('input[name=csrfmiddlewaretoken]').val(),
'data': $("#ListFile").val()
}
/*$.ajax({
type: 'POST',
url:'/list/create/',
cache:false,
dataType:'json',
data:data,
success: function(result) {
console.log("ok")
}
});*/
}
django views.py:
def createlist(request):
if request.method == 'POST':
file = request.FILES
here not getting file.I know getting file using form action.But here i want to post file through javascript because i want response back to javascript after success.
Clearly i want that file in views.py by request.FILES
When uploading files, your form must have this attribute:
enctype='multipart/form-data'
like this:
<form id="form" enctype='multipart/form-data'>
This might help you understand.
You have to use a FormData object and a slightly modified version of basic ajax post:
var data = new FormData();
var file = null;
//when uploading a file take the file
$("#your-file-input-id").on("change", function(){
file = this.files[0]
});
//append the file in the data
data.append("file", file);
//append other data
data.append("message", "some content");
$.ajax({
url: '/path',
type: 'POST',
data: data,
contentType: false,
processData: false,
success: function (data, status, xhr) {
//handle success },
error: function (data, status, xhr) {
//handle error
}
});
In Django you will find the file in request.FILES['file'].
I hope this is helpful.

Categories

Resources