Ajax python how to post data - python

Sorry guys, maybe this has been asked before. But I googled around for several days and still cannot solve the problem. I am developing a chatting system using Google App Engine with Python. I would like the user to enter her/his message and click "Submit" button. That action will trigger an Ajax post function "addMsg()" to POST the message to class Chat (URL: "/chat"), which will add the message to datastore. There is another Ajax function "updateMsg()" which will update the message list periodically.
The code works fine for message updating, however, I am not able to post the message correctly. Can anybody help me? Thanks. Here are my codes:
chat.html:
<p>
<form method="" action="">
<input type="text" name="message" size="60" /><br />
<input type="button" value="Submit" onclick="addMsg('message')" />
</form>
</p>
<div id="chatcontent"> </div>
<script>
function addMsg(message) {
$.ajax({
type: "POST",
url: "/chat",
data: {'message': message},
cache: false
});
}
</script>
<script>
$(document).ready(function() {
function updateMsg() {
$.ajax({
url: "/message",
cache: false,
success: function(returndata){
$("#chatcontent").html(returndata);
}
});
setTimeout(updateMsg, 4000);
}
updateMsg();
});
</script>
message.html:
{% for chat in chatlist %}
<p>
{{ chat.text }} ({{ chat.user.account }}) {{chat.created|date:"D d M Y" }}
</p>
{% endfor %}
chat.py:
# Called by URL "/chat"
class Chat(webapp2.RequestHandler):
def post(self):
message = self.request.get('message')
newchat = ChatMessage(user=self.session['userkey'], text=message, created=datetime.datetime.now())
newchat.put()
# Called by URL "/message"
class Message(webapp2.RequestHandler):
def get(self):
que = db.Query(ChatMessage).order('-created')
chatlist = que.fetch(limit=100)
render(self, 'message.html', {'chatlist': chatlist})
# Note: render() is a function to be imported, which is just a normal template rendering function. It works fine and is omitted here.

Chat.html
<p>
<input type="text" name="message" size="60" /><br />
<input type="button" value="Submit" onclick="addMsg()" />
</p>
<div id="chatcontent"> </div>
<script>
function addMsg() {
var message = $('input[name=message]').val();
$.ajax({
type: "POST",
url: "/chat",
data: {'message': message},
cache: false
});
}
</script>

Related

django: request.POST.get() returns NoneType

I am work from data acquired from an html form.
I am currently failing to capture the data on the server side. Every input returns "NoneType" on the server.
I feel like I tried everything that I could find around here, notably changing id for name in the html form, nothing works.
here is what I got so far:
views.py:
def quadriatransport_simulationView(request):
return render(request, "simulation.html")
#csrf_exempt
def compute(request):
destination = request.POST.get("destination")
nombre_de_palettes = request.POST.get("nombre_de_palettes")
poids_par_palette = request.POST.get("poids_par_palette")
Optimisation_prix = request.POST.get("Optimisation_prix")
Optimisation_delai = request.POST.get("Optimisation_delai")
result = {"destination":destination}
print(result)
return JsonResponse({"operation_result": result})
results returns a dictionnary where destination is None
now here is what I have been able to do on the webpage
<form method="POST">
{% csrf_token %}
<label><h3>Input variables to calculate EOQ:</h3></label>
<br>
<br>
<span>Destination (departement) <input type="text" id="destination">
<br>
<br>
<span>Nombre de palettes <input type="text" id="nombre_de_palettes">
<br>
<br>
<span>Poids par palette <input type="text" id="poids_par_palette">
<br>
<br>
<span>Optimiser prix <input type="checkbox" id="Optimisation_prix">
<br>
<br>
<span>Optimiser délai de livraion <input type="checkbox" id="Optimisation_delai">
<br>
<input id="ajax-call" type="submit" value="Simuler">
</form>
<p id="ajax"></p>
and here is my js script inside of the webpage
<script>
document.querySelector("#ajax-call").addEventListener("click", event => {
event.preventDefault();
let formData = new FormData();
formData.append('destination', document.querySelector("#destination").value);
formData.append('nombre_de_palettes', document.querySelector("#nombre_de_palettes").value);
formData.append('poids_par_palette', document.querySelector("#poids_par_palette").value);
formData.append('Optimisation_prix', document.querySelector("#Optimisation_prix").value);
formData.append('Optimisation_delai', document.querySelector("#Optimisation_delai").value);
let csrfTokenValue = document.querySelector('[name=csrfmiddlewaretoken]').value;
const request = new Request('{% url "compute" %}', {
method: 'POST',
body: formData,
headers: {'X-CSRFToken': csrfTokenValue}
});
fetch(request)
.then(response => response.json())
.then(result => {
const resultElement = document.querySelector("#ajax");
resultElement.innerHTML = result["operation_result"];
})
})
</script>
Not sure what is wrong with this, I have successfully used the same structure for other projects and it worked. I have been struggling with it for hours that I can't see straight. Hopefully someone can see where I messed up!
You misspelled destination in your formData
formData.append('destination', document.querySelector("#destination").value);

How to return single string value from flask to Html label tag?

I am trying to interact with my machine learning model where I can get the input value to the flask route method from HTML but not able to pass on the response with a string value to the ajax query.
THe click of the button hits the ajax function and does goto the flask route function, but it doesn't even hit the success or error part of the ajax function.
Gives 405 Method not Allowed error.
127.0.0.1 - - [12/Oct/2020 13:15:17] "POST / HTTP/1.1" 405 -
I am new to Flask and not aware of data binding options. Any help would be appreciated.
HTML PART
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="{{ url_for('static',
filename='css/bootstrap.min.css') }}">
<title>Twitter Sarcasm Detection</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js">
</script>
<script src="static/js/signUp.js"></script>
<style>
h1 {
margin-top: 13rem;
color: chocolate
}
p{
margin-top: 36px;
}
.form-group{
margin: 3rem !important;
}
</style>
</head>
<body>
<div class="container" style="text-align:center">
<h1>Twitter Sarcasm Detection</h1>
<p>Enter the text below to find out if its Sarcastic or not!</p>
<form action="http://localhost:5000/" method="post">
<div class="form-group">
<input type="text" class="form-control" id="userText" name="userText">
</div>
<button id="submit" class="btn btn-primary">Submit</button>
<input type="reset" value="Reset" class="btn btn-primary">
<div class="form-group">
<label id="prediction" name="prediction"></label>
</div>
</form>
</div>
AJAX query in the script file
$(function(){
$('#submit').click(function(){
$.ajax({
url: '/predictSarcasm',
data: $('form').serialize(),
type: 'POST',
success: function(response){
$('#prediction').val(response.result);
},
error: function(error){
console.log(error);
}
});
});
});
FLASK Code
from flask import Flask, render_template, json
from joblib import load
pipeline = load("text_classification.joblib")
def requestResults(text):
tweet = pipeline.predict([text])
if tweet == 0:
return "Not-Sarcastic"
else:
return "Sarcastic"
app = Flask(__name__)
#app.route("/")
def home():
return render_template('Index.html')
#app.route('/predictSarcasm', methods=['POST'])
def predictSarcasm():
text = request.form['userText']
prediction = requestResults(text)
return json.dumps({'status':'OK','result':str(prediction)});
if __name__ == "__main__":
app.run(debug=False)
you don't need to use forms for ajax
Html Code
<h1>Twitter Sarcasm Detection</h1>
<p>Enter the text below to find out if its Sarcastic or not!</p>
<div class="form-group">
<input type="text" class="form-control" id="userText" name="userText">
</div>
<button id="submit" class="btn btn-primary">Submit</button>
<input type="reset" value="Reset" class="btn btn-primary">
<div class="form-group">
<label id="prediction" name="prediction"></label>
</div>
</div>
Ajax Code
$('#submit').click(function(){
$.ajax({
url: '/predictSarcasm',
contentType: "application/json",
data: JSON.stringify({ "text": $('#userText').val()})
type: 'POST',
success: function(response){
$('#prediction').val(response.result);
},
error: function(error){
console.log(error);
}
});
});
Python Code
from flask import jsonify
#app.route('/predictSarcasm', methods=['POST'])
def predictSarcasm():
json= request.get_json()
text=json["text"]
prediction = requestResults(text)
return jsonify({"status":"OK",'result':str(prediction)})

Get data to a python variable from a html input?

I am new to python. I need to get data from a html input to a python variable. But I can't find a way to do this. It shows output as None, None, None for output.
It doesn't print out the data too. How can I fix this issue?
This is the code in html file.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type=text/javascript>
$(function() {
$('button#add-income').bind('click', function() {
$.getJSON('/add_income',
function(data) {
//do nothing
});
return false;
});
});
</script>
<form class="add-income-box" method="POST" action="">
<div class="add-income-expences-top-div">
<label>INCOME</label>
</div>
<div class="add-income-expences-label-div">
<label class="add-income-expences-date-lbl">Date : </label>
<label class="add-income-expences-details-lbl">Details : </label>
<label class="add-income-expences-amount-lbl">Amount : </label>
</div>
<div class="add-income-expences-input-div" id="div1">
<input class="add-income-expences-date-input" name="i_date" value="{{request.form.i_date}}">
<input class="add-income-expences-details-input" name="i_details" value="{{request.form.i_details}}">
<input class="add-income-expences-amount-input" name="i_amount" value="{{request.form.i_amount}}">
</div>
<button class="add-income-expences-bottom" id="add-income">ADD</button>
</form>
this is the code in python file
#app.route('/add_income', methods=["GET", "POST"])
def add_income():
i_date = request.form.get('i_date')
i_details = request.form.get('i_details')
i_amount = request.form.get('i_amount')
print(i_date)
print(i_details)
print(i_amount)
return "nothing"
output :-
None
None
None
127.0.0.1 - - [31/May/2020 16:56:07] "GET /add_income HTTP/1.1" 200 -
Change this form tag action attribute
<form class="add-income-box" method="POST" action="{{ url_for('update_project')}}">
In this way, when you click on button it will call the method specified in action attribute.
and if you want to call this API using AJAX then make use of JSON to send data. And if you want to send data using form then remove the Ajax code and change the code as above suggested and click on the button and you will not get the form data.

html form validation combined with flask and python

I have a web app that collects some data in text boxes then sends them to a python script that is running with flask
I have found two ways of submitting the form.
my button manages to collect the data and send it of to python and retires the answer from python but does not validate the inputs
my input tag manages to validate the text buttons but clears the form and does not manage to send the data of to the python script for processing.
I would like to do aspects of both buttons , I would like to validate , send data to python and retired the data.
Any ideas how to combine the function of the input submit and the button into one clickable item that validates and submits?
Any help much appreachiated
{% extends "layout.html" %}
{% block body %}
<script type="text/javascript">
$(function() {
var submit_form = function(e) {
$.getJSON($SCRIPT_ROOT + '/add_numbers', {
nm_height: $('input[name="nm_height"]').val(),
mn_material: $('input[name="mn_material"]').val(),
lc_height: $('input[name="lc_height"]').val(),
li6_enrichment_fraction: $('input[name="li6_enrichment_fraction"]').val()
}, function(data) {
$('#result').text(data.result);
$('input[name=nm_height]').focus().select();
});
return false;
};
$('#calculate').bind('click', submit_form);
//$("#myform").bind('ajax:complete', submit_form);
$('input[type=text]').bind('keydown', function(e) {
if (e.keyCode == 13) {
submit_form(e);
}
});
$('input[name=a]').focus();
});
</script>
<p>
<form name="myform" id="myform" >
<!--<form action="#" method='POST GET'>-->
<p>Height of neutron multiplier pebble bed <input type="number" size="10" name="nm_height" min="10" max="140" step="any" required placeholder='10 to 120'> mm </p>
<p>Neutron multiplier material <input type="text" size="10" name="mn_material" required placeholder='Be or Be12Ti'> Be or Be12Ti</p>
<p>Height of lithium ceramic pebble bed <input type="number" size="10" name="lc_height" min="10" max="140" step="any" required placeholder='1 to 60'> mm </p>
<p>Lithium 6 enrichment <input type="number" size="10" name="li6_enrichment_fraction" min="0" max="100" step="any" required placeholder='60 to 100'> %</p>
<button id="calculate" type="submit">predict TBR</button>
<input id="calculate" type="submit"></input>
</form>
TBR =<span id="result">?</span>
<br>
The TBR is quoted with a 95% <a href='http://www.stat.yale.edu/Courses/1997-98/101/confint.htm'> confidence interval </a>
<!--<p>calculate server side-->
{% endblock %}
I am in the same case and I have decided to use either regular expressions in the validation or just javascript .
regular expression is more powerful and faster but needs time, javascript is easier and slower. so it is a deal.
Let the backend handle the validation using something like WTFForms. Then all you need to worry about is submitting the data to the API endpoint and dealing with the responses that come back.
Avoid doing any validation strictly on the frontend because it's not secure and more likely to be tricked compared to backend validation.
{% extends "layout.html" %}
{% block body %}
<script type="text/javascript">
$('#myform').on('submit', function() {
var res = $.ajax({
url: '/add-numbers'
data: $(this).serialize(),
...
});
res.done(function(data) {
// get successful calculation back...
});
res.fail(function() {
// handle validation or calculation errors...
});
});
</script>
{% endblock %

jQuery autocomplete doesn't want to send particular POST data

I'm trying to add an item (fund). The autocomplete succeeds in showing all the funds. It should retrieve the fund.id corresponding to that 'fund'. If I could get another set of eyes on this, it would be greatly appreciated...
Just to be clear: I'm not getting a specific error. My view just redirects if there is no 'fund' in the POST. I'm just trying to figure out why my autocomplete isn't posting the fund POST value' (fund.id).
-- Thank you advance
Template:
<script type="text/javascript" src="{{ STATIC_URL }}js/autocomplete/add_fund_autocomplete.js"></script>
...
<form method="POST" action="/profile/edit/">
{% csrf_token %}
<input type="hidden" name="fund" id="id_fund" />
<div class="inline-block">
<label for="id_omnibox">Fund</label>
<input id="id_omnibox" name="omnibox" placeholder="Enter a fund name or search for an existing..." type="text" />
</div>
<div class="input-prepend inline-block">
<label for="id_amount">Allocation</label>
<span>$</span>
<input id="id_amount" name="amount" type="text" placeholder="Enter amount" />
</div>
<button class="add" type="submit" name="add_position">Add</button>
</form>
add_fund_autocomplete.js:
$(document).ready(function() {
$.get('/autocomplete/funds/', function(data) {
var completions = new Array();
var dict = JSON.parse(data, function(key, value) {
completions.push(key);
return value;
});
$('#id_omnibox').autocomplete({
source: completions,
minLength: 2,
select: function(event, ui) {
$('#id_fund').val(dict[ui.item.value]);
}
});
});
});
(autocomplete)View:
#login_required
def funds(request):
funds = Fund.objects.exclude(name='Placeholder')
result = {}
for fund in funds:
result[fund.name] = str(fund.id)
return HttpResponse(json.dumps(result))
For example:
Adding the fund Hoth Ltd with an amount of $123.
Hoth Ltd's fund.id should be 1.
POST data
POST
---------------------------------------------------------
Variable Value
---------------------------------------------------------
fund u'' #empty? :\
csrfmiddlewaretoken u'436f77eb2023043be2f5242bb0443d80'
omnibox u'Hoth Ltd'
amount u'123'
add_position u'' #Just a trigger used in my view
The variable dict is undefined when the select callback function is called.
You can just use ui.item.value.

Categories