Get textarea value from HTML page to Python Flask using Javascript - javascript

I'm having a bit of trouble with figuring out how to get a post from Javascript to work, to my Python Flask server.
Here's the important part of what I've got in my html file
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js </script>
<script type=text/javascript>
$('a#test').bind('click', function() {
var textBox = document.getElementById('targetTextArea').value;
$.post('/postmethod', {text: textBox} );
});
</script>
<!--textarea-->
<textarea rows="1" cols="20" id="targetTextArea">
</textarea>
<!--button-->
<form method="post" role="form">
<a href=# id=test>
<input type="button" value="submit" id="submit" onClick="writeOut()">
</a>
</form>
and here's what I've got in my Python flask file
#app.route('/postmethod', methods = ['POST'])
def postmethod():
data = request.form['text']
print "Hello world!"
print data
return data
When I run my python script the textarea and button are there as they should be, but when I type into the textarea and click the button nothing is printed. Please help.

You try with the long way?
Replace $.post('/postmethod', {text: textBox} );
for
$.ajax({
method: "POST",
url: "postmethod", //here can be '/postmethod'
dataType: 'text',
data: {text: textBox},
success: function(result) {
// example
$('body').html(result)
}
});
This should print on page the content of the variable "data" of python code.
Another thing,
I see that you are using two ways for the submit button, if you use
$('a#test').bind('click', function() { //code });
then, the onClick="writeOut()" is not neccessary.
I hope you find it useful, regards.

id's value should be in quotes
<a href="#" id="test">
<input type="button" value="submit" id="submit" onClick="writeOut()">
</a>

The solution I found was to add
$(function() {
});
around it
$(function() {
$('a#test').bind('click', function() {
var textBox = document.getElementById('targetTextArea').value;
$.post('/postmethod', {text: textBox} );
return false;
});
});
and also the return false prevents the page of redirecting
sorry guys, I'm new to Javascript. Thank you very much!

Related

how to use form data every second with ajax

I'm very confused. Can anyone help me?
Here is the code:
index.php =>
<html>
<head>
<script src="jquery-1.2.6.min.js"></script>
<script>
function chk(){
var name = $('#name').val();
$.ajax({
type:"post",
url:"test.php",
data:{name:name},
cache:false,
success:function(html){
$('#msg').html(html);
}
});
return false;
}
setInterval (function chk() , 1000);
</script>
</head>
<body>
<form>
<input type="text" id="name">
<input type="submit" value="submit" onclick="return chk();return false;">
</form>
<p id="msg">Loading</p>
</body>
</html>
and test.php =>
<?php
$name = $_POST['name'];// $name is constant for each request that submited from ajax($name is a parameter)
$api -> new server_data();
$results = $api ->show($name);
print_r($result);//This data updates from server in every second
=======================================================================
I'm trying to connect to an API, but in that API, data changes every second and I have to see these changes. On the other hand, I have to set default values with the form.
But the problem is here that each time the form submits, the posted value in test.php will be null, and the ajax request will not work.
Can anyone help me?
Try adding a name attribute to your name input box element.
<input type="text" id="name" name="name">
Your PHP $_POST['name'] variable is looking for an input element with the html attribute name="name", whereas you only had an html attribute id="name".
Source: PHP: Dealing with Forms

JQueryUI Progress Bar doesn't maintain value after update via form submit

I'm trying to set up a JQuery Progress Bar to update when the user submits a form (the final code will be more complex and dynamic, but I'm just trying to learn how the progress bar works first).
The simple code that I'm trying to debug is:
<body>
<form id="form1" method="GET" runat="server">
<div>
<h1>Test</h1>
<input type="submit" value="Start Test"/>
</div>
</form>
<div id="progressbar"></div>
<script type="text/javascript">
$("#progressbar").progressbar({
value: 25
});
$("#progressbar > div").css({ 'background': 'Green' });
$(document).ready(function () {
$("#form1").submit(function () {
$("#progressbar").progressbar({ value: 75 });
});
});
</script>
</body>
It's just a simple form that initializes a progress bar to 25%, and runs a .submit function that sets the value to 75%. I know that the submit code is getting called because if I click the Submit button repeatedly, I see the 75% value flash on and off in the progress bar.
My question is: How do I get the value to stay selected once it's changed by the .submit function?
Thanks In Advance!
UPDATE:
Thanks for the advice #charlietfl :-) New to the whole posting thing :-)
Here is the ajax-based code I have...
<body>
<form id="form1" method="GET" runat="server">
<div>
<h1>Test</h1>
<input type="submit" value="Start Test"/>
</div>
</form>
<div id="progressbar"></div>
<script type="text/javascript">
$("#progressbar").progressbar({
value: 25
});
$(document).ready(function () {
$("#form1").submit(function () {
$.ajax({
url: "JQueryProgressTest.aspx/GetProgress",
type: "GET",
success: function (data) {
$(".selector").progressbar({value: data});
}
});
});
});
</script>
</body>
Still not updating...don't even see the value flash anymore.
Thanks!
Bob
FINAL UPDATE: Needed to also add some JSON stuff to get the callback from the aspx page to work. Below is the fully working code for anyone else who needs it:
ASPX Code-Behind:
public partial class JQueryProgressTest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static int GetProgress()
{
// Put any code to update the progress bar here
return 50;
}
}
And the body of the aspx page itself:
<body>
<form id="form1" method="GET" runat="server">
<div>
<h1>Test</h1>
<input type="submit" value="Start Test"/>
</div>
</form>
<div id="progressbar" style="border-color: lightgreen;"></div>
<script type="text/javascript">
$("#progressbar").progressbar({
value: 25
});
$("#progressbar > div").css({ 'background': 'Green' });
$(document).ready(function () {
$("#form1").submit(function (event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "JQueryProgressTest.aspx/GetProgress",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$("#progressbar").progressbar({ value: response.d });
},
failure: function(response) {
alert("Error in calling Ajax:" + response.d);
}
});
});
});
</script>
</body>
Thanks again to #charlietfl for all the help!
There is no state saving between page loads. When you submit the form it will reload page based on the form action.
Some choices are:
Use ajax to submit form so user doesn't leave page
Use a javascript variable defined in your server code and passed to script tag to set progress, adjust variable according to submit or not
Store state in cookie or localStorage and set value based on stored value

pass javascript variables into grails params

So I need to pass javascript variables into grails parameters to build and download a file. So initially did this with ajax just to learn that ajax doesn't do downloads. Initially this worked like so:
<script type="text/javascript" charset="utf-8">
function myFunction() {
jQuery.ajax({
url: "Search/download",
type: "POST",
data: {facets: visualSearch.searchQuery.facets()}
});
}
</script>
<input type="button" onclick="myFunction()" value="download">
While this passed the mapping correctly, this didn't do downloads.
So now I am want to do something similar with a g:link
<g:link controller="Search" action="test" params="[facets: '\$(visualSearch.searchQuery.facets())']" >TEST GRAILS</g:link>
But all I get in the params in the controller are
facets=$(visualSearch.searchQuery.facets())
action=test
controller=search
How can I fix this to pass the facets (whether parsed or unparsed) into the controller. Thanks!
Adding your javascript variable in params will not work. The g:link is executed on the server side and has no knowledge of your javascript values. You can remove this params and instead add code on the `onclick' event of your link to set your javascript values in the params.
Something like:
In the gsp page,
<g:link name="searchLink" controller="Search" action="test">TEST GRAILS</g:link>
and then in javascript (in the same page),
$(function() {
$('a[name="searchLink"]').bind('click', function() {
$(this).attr('href', $(this).attr('href') + '?facets=' + visualSearch.searchQuery.facets());
})
})
Basically you are using Grails to generate the hyperlink and then using JQuery to append a query string with the parameters to that href
Hope that helps.
What I tend to do in these cases is use the g:link to generate the URL, but then override the default behavior with jQuery to make the ajax call:
<g:link class="searchLink" controller="Search" action="test" params="[facets: '\$(visualSearch.searchQuery.facets())']" >TEST GRAILS</g:link>
$('.searchLink').on('click', function(e) {
e.preventDefault(); // prevent default link behavior
var $element = $(this);
var url = $element.prop('href');
$.post(url, function(data) {
// callback if you need it
});
});
From what you have I think you should create a form and submit it in the click event:
<script type="text/javascript" charset="utf-8">
function myFunction() {
$('<form>', {
"html": '<input type="text" name="facets" value="' + visualSearch.searchQuery.facets() + '" />',
"action": '${createLink(controller: "Search", action: "test")}',
"method": 'POST'
}).appendTo(document.body).submit();
}
</script>
<input type="button" onclick="myFunction()" value="download">
Or refactor your code to have a real html form and prepare the data for it before submit.

jQuery load(URL) not working when loading page-fragments?

I have this page, the first button is working good.
I want when press the second button to give me the link that is in the href, i tried like this , but i got the whole page , not just the value of the link , why please?
<html>
<head>
<script src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var url = "http://localhost/test/asdfasdf.php";
$("#button").on("click", function() {
$('body').load( url );
});
$("#button2").on('click',function(){
$('body').load( url +"#link" );
});
});
</script>
</head>
<body>
<input type="button" id="button" value="load" />
<input type="button" id="button2" value="search for a tag" />
</body>
</html>
I think you want a space:
$('body').load(url + " #link");
http://api.jquery.com/load/#loading-page-fragments
All you seem to want is the href of the a#link element at that URL. So instead of loading it into the <body>, just make the AJAX request, and look through the result:
$.ajax({
type: "GET",
url: "http://localhost/test/asdfasdf.php",
dataType: "html"
}).done(function (data) {
var the_link = $(data).find("#link");
alert(the_link.attr("href"));
});
And to put the href in the <body>, add this line in the .done() method:
$("body").html(the_link.attr("href"));
// or
$("body").append(the_link.attr("href"));
But if you actually want to load the a#link element into <body>, do what you had before, but then look for the a#link element and get its attribute:
$('body').load(url + " #link", function () {
var the_link = $("#link");
alert(the_link.attr("href"));
});
EDIT
You're trying to capture the href of the <a> on a different page. A try:
$.get(url+' #link', function(data) {
var $link = $(data).find('a').attr('href');
alert($link);
});
That is my very best guess, but its a shot in the dark.
Currently your code evaluates to .load('http://localhost/test/asdfasdf.php#link'), where #link is a useless fragment. You need a space to engender jQuery's special behavior of automatic DOM parsing and element loading.
$("body").load(url + " #link");
EDIT: to get the actual link value:
$.get(url).done(function (html) {
console.log($(html).find('#link').attr('href'));
});
You can also append to body inside of the .done callback.

Hidden form file POST in javascript

Because of a Flex bug uploading files in a secure environment, I'm attempting to hack together a workaround for this in javascript.
To do so, I'm attempting to create a hidden form in javascript, to which I'll attach a file and some xml meta data, then send it to the server in a multipart form post. My first thought is to get this to work in HTML and then port this javascript code into my Flex project.
My first problem is attaching the file to the hidden form in javascript. I'm doing something wrong here. I'm pretty inexperienced with javascript so if there's a better way to do this, I'm eager to learn.
Here's the code I'm current playing with.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>hidden form post demo</title>
</head>
<body>
<script>
//helper function to create the form
function getNewSubmitForm(){
var submitForm = document.createElement("FORM");
document.body.appendChild(submitForm);
submitForm.method = "POST";
submitForm.enctype = "multipart/form-data";
return submitForm;
}
//helper function to add elements to the form
function createNewFormElement(inputForm, inputType, elementName, elementValue) {
var inputElement = document.createElement("INPUT");
inputElement.name = elementName;
inputElement.type = inputType;
try {
inputElement.value = elementValue;
} catch(err) {
alert(err.description);
}
inputForm.appendChild(inputElement);
return inputElement;
}
//function that creates the form, adds some elements
//and then submits it
function createFormAndSubmit(){
var submitForm = getNewSubmitForm();
var selectedFileElement = document.getElementById("selectedFile");
var selectedFile = selectedFileElement.files[0];
createNewFormElement(submitForm, "HIDDEN", "xml", "my xml");
createNewFormElement(submitForm, "FILE", "selectedFile", selectedFile);
submitForm.action= "my url";
submitForm.submit();
}
</script>
<div id="docList">
<h2>Documentation List</h2>
<ul id="docs"></ul>
</div>
<input type="file" value="Click to create select file" id="selectedFile"/>
<input type="button" value="Click to create form and submit" onclick="createFormAndSubmit()"/>
</body>
</html>
You can see, I have a try/catch block in createNewFormElement. An exception is being thrown there, but the message says "undefined".
In FireBug, I can see that the elementValue is set to a File object, so I'm not really sure what's going on.
For security reasons, you cannot set the value attribute of an input[type=file]. Your current code doesn't need JavaScript, and can be written using pure HTML:
<form method="post" enctype="multipart/form-data" action="myurl">
<input type="file" value="Click to create select file" name="selectedFile" />
<input type="hidden" name="xml" value="my xml" />
<input type="submit" value="Click to create form and submit" />
</form>
If you want to, it's possible to dynamically add additional non-file form elements, by binding an event to the onsubmit handler.
<form ... onsubmit="addMoreinputs();" id="aForm">
...
<script>
function addMoreInputs(){
var form = document.getElementById("aForm");
// ...create and append extra elements.
// once the function has finished, the form will be submitted, because
// the input[type=submit] element has been clicked.
}
add
var dom=document.getElementById("formdiv");
dom.appendChild(submitForm);
in your createFormAndSubmit function.
and add <div id="formdiv" /> on your page.

Categories

Resources