I have a Flask application which has a page where the user can input a sentence. I want to take this user input and feed that into a Flask method which will perform some calculations on that sentence and then return the result (which is a string).
I would ideally like it to return on the same page, just underneath the form's submit button.
At the moment, I am trying to do this by using javascript. Here's what I have at the moment:
result.html
<head>
<script type=text/javascript>
$(function() {
$('a#test').bind('click', function() {
$.getJSON('/result_sentence',{
sentence: $('textarea[name="sentence"]').val()}, function(data) {
// do nothing
document.getElementById('display').innerHTML = data.result;
});
return false;
});
</script>
</head><body>
<!-- The form where the user inputs -->
<div id="interactive" style="margin-top:50px">
<textarea style="width:100%;" rows="3" name="sentence" placeholder="Enter your sentence"></textarea>
Predict
<label> I predict.. </label>
<p><span id='display'></span></p>
</div>
app.py
#app.route('/result_sentence')
def result_sentence():
sentence = flask.request.args.get('sentence')
pred = getPrediction(sentence)
return jsonify(result=pred)
Also, it should be noted that on the results.html, I have already called another Flask function which has redirected my Flask app to results.html and has displayed some charts.
So the main problem I am facing is that I am not sure why nothing happens when I click the button. To me it seems that when the button is clicked it should pass the sentence into the Flask function and perform the calculations.
I've looked at a bunch of questions that were already posted here on StackOverflow such as this one: Flask - Calling python function on button OnClick event
but they didnt really help me in this regard.
I don't really see where it is going wrong so I would appreciate any insight or help with this.
Thanks!
EDIT:
So it seems that the first problem is that the JS function doesnt get called at all when the button is clicked...
You need to use $.ajax with jquery. First, simply create an input box and button which, when clicked, will trigger the script to call the Ajax. In the HTML, the javascript will retrieve the user's input when the button is clicked, and the input will be sent to the flask route:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<input type='text' id='word'>
<button type='button' id ='retrieve'>Submit</button>
<div id='wordResult'></div>
</body>
<script>
$(document).ready(function() {
$('#retrieve').click(function(){
var word = $('#word').val();
$.ajax({
url: "/get_word",
type: "get",
data: {word: word},
success: function(response) {
$("#wordResult").html(response.html);
},
error: function(xhr) {
//Do Something to handle error
}
});
});
});
</script>
</html>
Then, create the route in app.py:
#app.route('/get_word')
def get_prediction():
word = flask.request.args.get('word')
return flask.jsonify({'html':getPrediction(word)})
Related
I'm searching for the best solution to display information which I store in PHP variable (which I get from a MySQL DB).
I was thinking to use jQuery. My questions:
With the input field I receive the number of the Member.
I store a new variable called $imgMember with the img name.
Questions:
I want to display this image each time a user enters a number at <div class="boxImageMember"> (which I already validated through PHP and made a variable ($imgMember) of it.
How should I access it? Do I need to store those variable with AJAX? Internal/external jQuery? Or do I need to think otherwise? Im stuck in my head.
Im totally stuck with the way I how to process this.
HTML:
<div id="header">
<div class="header-content">
<img src="img/logo-dqmih.png" width="60px">
</div>
</div>
<div class="container">
<div class="boxImageMember">HERE I WANT TO DISPLAY A USER IMAGE</div>
<div class="boxInformationMember"></div>
<form action="" method="post">
<input type="text" id="MemberNumberEntry" name="staffNumber">
<button type="submit" name="action">
</form>
</div>
jQuery:
$(document).ready(function() {
$("#MemberNumberEntry").focus();
$(document).on('submit',function(event, test){
event.preventDefault(); // Don't refresh the page
var MemberNumberEntry = $("#MemberNumberEntry").val();
console.log(MemberNumberEntry);
$(".boxImageMember" ).css("background-image", "url(../images/persons/NIT.jpg)"); // Change image (Not dynamic yet)
$(".boxInformationMember" ).text("Hi Test, welcome!");
// Reset value form entry
$('#memberNumberEntry').val('');
});
});
Your jQuery script would do something like this
$(document).ready(function() {
$("#MemberNumberEntry").focus();
$(document).on('submit',function(event, test){
event.preventDefault(); // Don't refresh the page
var MemberNumberEntry = $("#MemberNumberEntry").val();
//console.log(MemberNumberEntry);
$.ajax({
url: '/your-php-script.php',
method: 'POST',
data: {
MemberNumberEntry: MemberNumberEntry
},
success: function(response){
//If call goes well, you use the image here.
}
});
$(".boxImageMember" ).css("background-image", "url(../images/persons/NIT.jpg)"); // Change image (Not dynamic yet)
$(".boxInformationMember" ).text("Hi Test, welcome!");
// Reset value form entry
$('#memberNumberEntry').val('');
});
});
You're basically sending an HTTP POST request to your PHP script that will accept the image ID like a normal post request, using $_REQUEST or $_POST.
There are tonnes of options to configure with jQuery, you can look at the docs here. For more information on working with images in PHP and AJAX, this answer is useful.
this is my problem.
I have a startpage website on this address: http://battlestation.rocks/
It mostly revolves around a search bar in the front page that executes commands. Presently, every command is processed with php, like so:
if (isset($_POST['searchBar'])) {
$originalcommand = $_POST['searchBar'];
processcommand($originalcommand);
return;
}
With this, every command reloads the page, which is a waste as most of the times it just opens some link from the startpage. In other cases, the startpage is changed by the commands, and thus in those cases I would like the page to reload.
I've seen from other questions that you can have the page not reload with AJAX, but none of the answers I've seen send the form input to php for processing, nor do they include the option to reload if necessary.
I'm very much a hobbyist coder and have zero experience with AJAX, please don't get too technical on me. I'm obsessed with this startpage, I just need to get this working as intended. Please help!
If you use PHP directly then the page needs to reload. If you use AJAX then you can send it so without reloading. !-You need a new PHP file in which you process the input-! An example with jquery but works the same:
You normal site:
<form action=''>
<input type='email' id='email' placeholder='E-Mail' required=""/>
<input type='password' id='pwd' placeholder='Passwort' required=""/>
<button id='go_login'>Go</button>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$('#go_login').click(function() {
var bn = $('#email').val();
var pw = $('#pwd').val();
$.post('newphpsite.php', {'bn': bn, 'pw': pw}, function(data) {
alert(data); //send back echo from PHP
});
return false; //The form is not sent and does not reload the page.
});
</script>
newphpsite.php :
<?php
$bn = $_POST['bn'];
$pw = $_POST['pw'];
echo $bn."".$pw;
?>
?>
Yes, you should send the data via AJAX. One popular option is to use jQuery. Below is a simplified example using jQuery.
First, the HTML:
<input id="searchBar" name="searchBar" type="text" />
<button id="submit">Search</button>
<div id="searchResults"></div>
Next the jQuery:
<script type="text/javascript">
$("#submit").click(function() {
$.ajax({
type: "post",
url: "search.php", // Your PHP file
data: {
searchBar: $("#searchBar").val()
},
success:function(results) {
// Do something with your results
$("#searchResults").html(results);
}
});
});
</script>
trying to understand all this about AJAX, first of all I wanted to know how to refresh a page and keep my position on the page, which was possible, however, that was not the case on form post, that just jumped me right back to the top.
So after searching around on how to solve that, posting with AJAX seems to be my solution, I just can't seem to get all of it.
<form method="post" action="~/getAJAX.cshtml" id="ajaxform">
<input type="text" name="kg" id="kg" />
<input type="submit" />
</form>
<script type="text/javascript">
$(function () {
$('#ajaxform').submit(function (event) {
event.preventDefault(); // Prevent the form from submitting via the browser
var form = $(this);
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize()
}).done(function (data) {
// Optionally alert the user of success here...
}).fail(function (data) {
// Optionally alert the user of an error here...
});
});
});
</script>
This is the code I have so far.
The thing I do not understand is what exactly should be on my "action" page?
At the moment I put this on my action page.
var db = Database.Open("Database");
var getKG = Request.Form["kg"];
var query = "SELECT * FROM Test WHERE kg = #0";
db.Execute(query, getKG);
This is just a test, I don't really know what to expect or anything, I would like to show the results on the page I post from, any guiding for this please?
Note that this is not a MVC project, therefore my problems with finding any good solutions or help, it's just normal CSHTML files.
What I am trying to do
I have a HTML form which looks like this:
[input text field]
[submit button].
I want the output results to display in only a small part of the page (don't want to refresh the entire page after the button is clicked).
What I have done so far
I am using jquery load() as follows:
<script type="text/javascript">
function searchresults(id) {
$('#myStyle').load('displaysearchresults.php?id=' + id ; ?>);
}
</script>
Results will appear in a div which is exactly what I want:
<div id='myStyle'></div>
The problem
The script above works just fine (I used a variation of it elsewhere). But I have 2 problems:
1-How to call the load() script from the form. I tried this but it doesn't work:
<form id="form" name="form" method="post" action="searchresults('1')">
2-If I am not able to call the load() script from the form, how do I pass what is into the input text field to the load() script so in the end it can be proceessed by the displaysearchresults.php file???
Thanks
Currently its not working since you have a typo:
function searchresult(id) {
/^ no s
$('#myStyle').load('displaysearchresults.php?id=' + id ; ?>);
}
Here:
action="searchresults('1')"> // this should be on the onsubmit
^
Since you're intention is to submit the form without reloading, you could do something like:
$('#form').on('submit', function(e){
e.preventDefault();
$.ajax({
url: 'displaysearchresults.php',
data: {id: 1},
type: 'POST',
success: function(response) {
$('#myStyle').html(response); // assuming the markup html is already done in PHP
}
});
});
Of course in the PHP side, just call it like a normal POST variable:
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$id = $_POST['id'];
// other stuff you have to do
// echo markup stuff
exit;
}
Ok I have been able to do what I wanted to do, i.e., displaying search results in part of the page without reloading.
Actually it is not necessary to use the ajax load() function. You can do it with the script below:
<form id="form" method="POST">
<input type="text" id="textbox" name="textbox" />
<input type="submit" name="test" />
</form>
<div id="myStyle"></div>
<p>
<script src="jquery-1.10.2.min.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
$('#form').on('submit', function(e){
e.preventDefault(); // prevent the form from reloading
$.ajax({
url: 'displaysearchresults.php',
type: 'POST',
dataType: 'html',
data: {text:$('#textbox').val()},
success: function(response) {
$('#myStyle').html(response);
}
});
});
});
</script>
So what is this doing:
It will "read" what the user entered in the textbox,
When the user click the "submit" button, it will put that into a POST variable and send it to "displaysearchresults.php" without reloading the page,
The search results will be displayed between the "mystyle" div.
Pretty nice.
Note for beginers: do not forget to copy the jquery file to your root folder otherwise ajax just won't work.
i use django make a website .
i want to let people create group in my website .so i use html form to let them fill in the info and upload an image as the group logo.
as i want to let people preview the logo,so i use ajax upload the picture file first.i add 2 buttons in the page,button1 is for upload picture file in ajax way,button2 is for post the whole form to the server .for the ajax upload picture ,i use this plugin http://malsup.com/jquery/form/
ok here is the code
<!doctype html>
<html>
<head>
<script src="jquery-1.10.2.min.js"></script>
<script src="jquery.form.min.js"></script>
<meta charset="utf-8">
<title>test</title>
</head>
<body>
<form id="test" action="/accounts/signup/" method="post">
<input type="text" id="text" name="text" />
<input type="file" name="file" id ="file" /> <span >submitpicture</span>
<span>confirm</span>
</form>
<script language="javascript" type="text/javascript">
$("document").ready(function(){
$("#tnpicsubmit").click(function(){
$("#form").submit(function(){
var options={
url:"/article/nodetpic/",
type:"POST",
datatype:"json",
};
$("#form").ajaxSubmit(options);
return false;
}).submit();
});
$(".signup").click(function(){
$("#test").submit()
});
})
</script>
</body>
</html>
this code works,but not well.
because ,the first time i choose one picture,and click the button id #tnpicsubmit,yes the picture uploaded to my host,i through every thing is ok .then i test the 2nd time,and this time ,the same picture file ,upload 2 times,i find 2 same pictures in the host ,and i test 3rd time ,same picture upload 3 times.
now i know the problem where is .i think the problem is ,every time i click the button id #tnpicsubmit,it add the same function to the form submit event,that is why every time i get +1 times picture uploaded.
how to solve this problem ?i mean,just one click ,upload one picture one time for ajax file upload.
As i understand your question, try using one():
$("#form").one('submit', function(){...});
You are adding the submit handler inside the click event and then calling it. It is adding another handler every time you click the button. Solve the issue by moving the submit handler outside the click event.
<script language="javascript" type="text/javascript">
$("document").ready(function(){
$("#form").submit(function(){
var options={
url:"/article/nodetpic/",
type:"POST",
datatype:"json",
};
$(this).ajaxSubmit(options);
return false;
});
$("#tnpicsubmit").click(function(){
$("#form").submit();
});
$(".signup").click(function(){
$("#test").submit()
});
})
</script>
I don't see #tnpicsubmit in the html. But it could be an so you can use less JavaScript.