Javascript to execute after python function in Flask - javascript

Am new to coding and learning Python. Currently working on Flask to make some webapp. For one of the project I am trying to achieve the below
(1) On a webpage , I have a button when clicked, I pass the values inside the textbox to Python function. Which does some operation of getting the data from the database and it create an html which stores that database query output into a table.
(2) When this HTML file is generated with the table inside, I want to display the same in my webpage in an iframe (the page generates iframe automatically)
The way I have achieved this is having 2 buttons, One button to pass the values to Python function and second button to display the generated HTML into an iframe.
<br />
<input type='submit' value='Process Query' class="savebtn" name='Submit' />
<br />
<input type='button' value='Submit Query' class="savebtn" name='Submit' onclick="myFunction()" />
. . .
<script>
function myFunction() {
var iframe = document.createElement('iframe');
$('iframe').not(this).remove();
var html = '
<body>Foo</body>';
iframe.src = 'http://192.xx.xx.xx:10000/Table.html';
iframe.height = "500";
document.body.appendChild(iframe);
console.log('iframe.contentWindow =', iframe.contentWindow);
}
</script>
I think the second button is unnecessary but am not sure how can I do this?
Apologies if this is found too basic for many but as i said , am starting to learn coding.

If I understand your problem correctly, what you want is to first process the text and generate some html, and then display this same html to a user. If that is the case, what you need is an asynchronous request.
With an asynchronous request, you send data off to the server (without reloading the web page) and when you receive a response, you do something with it. A very crude code would be something like
function clickButton(){
fetch("/<path_to_server>/")
.then(function(result) { // This is the response from the server
return result.json(); // convert it to json
})
.then(function(data) {
// process your returned data
// e.g. data.generated_table could be your html output
// which you can now display in your iframe
})
}

Related

ASP.net Core Razor Pages - Get HTML of a specified div in Code-Behind

I am trying to get a specified div on my page in code-behind to convert the html to rtf using HtmlToOpenXml.
At this stage I have a hidden textarea/input to save the html into a Request I can use in the code-behind. But either way using javascript to set the text inside of the textarea/input sets some weird whitespaces, which get converted to the OpenXML as well.
So basically I am wondering how to get the content of a specific div-Tag in code-behind, so the converter can use the html.
For everyone wondering why I need that: I am using TinyMCE for the user to generate the basic design of a document, which contains lists of sentences with dropdowns and inputs which will get filled on using the tool. These entries get pasted into the div and should render as text on download and not as dropdowns or inputs.
Thanks in advance.
You can get the specific html by using $("#divname").get(0).outerHTML; and then post it to server side:
<div id="thisdiv"> //will get div by this id
<div>Hello</div>
</div>
<input type="button" id="btn1" value="Send" onclick="SendDiv()" />
#section Scripts
{
<script>
function SendDiv() {
var divhtml = $("#thisdiv").get(0).outerHTML;
$.ajax({
url: "your path",
data: { mydiv: divhtml },
method: 'POST'
});
}
</script>
}
Result:

How to pass data to parent in JavaScript and HTML

I am creating a website in plain HTML, CSS and JavaScript and want to send data between two pages (child and parent). Here is a simple example of what I want to do.
CHILD PAGE:
<html>
<head>
<title>Child</title>
</head>
<body>
<input type='text' placeholder='Enter data to be sent.' id='data'>
<button onclick='work()'>Send</button>
<script>
function work(){
var data = document.getElementbyId('data').value
//Code to send this data to parent.
}
</body>
</html>
PARENT PAGE:
<html>
<head>
<title>Parent</title>
</head>
<body>
<h1 id='data_recieved'></h1>
<button onclick='work()'>Recieve</button>
<script>
function work(){
var data = document.getElementbyId('data_recieved').innerHTML;
//Code to receive the data from child
}
</body>
</html>
I will be very grateful for your help.
DOM don't work across pages. You have to use a storage medium, it can be client side i.e localStorage, 'sessionStorage' or cookies using JavaScript. Or you can use a backend where you can store the values in some sort of database.
Another way to pass data from one page to another is to use a <form>, fill in certain fields and submit it so that it gets sent as POST or GET data to the next page. In your case I believe this should be the ideal scenario. If you do not have a backend best option is to send form data using GET method so that it gets appended to the URL as query parameters.
e.g on parent HTML page
<form action='child.html' method='get'>
<input type='text' name='somedata' value='whatever'/>
<input type='submit'/>
</form>
and on child page you can use JavaScript to get the query parameters using JS
<script>
var somedata = getParameterByName('somedata');
function getParameterByName(name, url = window.location.href) {
name = name.replace(/[\[\]]/g, '\\$&');
var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
</script>
There are of course other more sophisticated and advanced ways to achieve the same results but those might not be what you are looking for.
Sending data to a page doesn't mean anything, you have to send data to a program or to a server that will be able to interpret this data.
The easiest way is to send an HTTP request to the server, either by ajax if you don't want the navigator to close the page, or by just sending the form or requesting a link. You can then interpret the request using any program you want (PHP being one of the most used option).
Firstly, I noticed that your <input /> tag is missing the / to self close.
You will need to add a Javascript file to your project. Import the file into both html pages using a <script> tag.
You can get rid of the work() functions in both pages. Rather, you will store the onClick events in the Javascript file. Additionally, you will have a data object in the Javascript file that will store the data when the 'sent' button is clicked and retrieve it when the 'receive' button is clicked.
Add an id to the 'send' button on the child page:
<button id="send-button">Send</button>
In the Javascipt file:
let data = ''; //data will start off as an empty string
$("send-button").on('click', function(){
data = $("data").val(); //gets the data from your <input /> on the child page
})
Now add an id to the 'receive' button on the parent page:
<button id="receive-button">Receive</button>
And back to the Javascript file where the data will be stored in the data object:
$("receive-button").on('click', function(){
$("data-received").val(data); //changes the value of the <h1> to be the data
})

Pass Javascript variable to another page via PHP Post

I am having two php pages:
page 1:
<form class="form-horizontal" role="form" method="post" action="Page2.php">
<button id="place-order" class="btn btn-lg btn-success">Place Order</button>
<div id="ajax-loader" style="display:none;"><img src="images/ajax-loader.gif" /></div>
</form>
<script>
var id = Math.random();
$(document).ready(function() {
$('#place-order').on('click', function() {
$(this).hide();
$('#ajax-loader').show();
});
});
</script>
As on form, it redirects to Page2.php, I want to pass the Javascript variable "id" from Page1 to receive it in Page2.
I have tried using cookies, but need an alternative approach.
I am not understanding the transistion from PHP to JS and vice-versa. Help is appreciated.
Thanks in advance
Dear you can do it very easily with ajax. Ajax has data attribute which helps you pass your data from javascript to another page.
This link will help you a lot
https://api.jquery.com/jquery.ajax/
You can use session storage or cookies.
Example for session storage:
// First web page:
sessionStorage.setItem("myVariable", "myValue");
// Second web page:
var favoriteMovie = sessionStorage.getItem('myVariable');
You could use a query string to pass the value to the next page.
Add an ID to the form
<form class="form-horizontal" role="form" method="post" action="Page2.php" id="order-form">
Update the action of the form to add this query string from our JS variable
var id = Math.random();
$('#order-form').attr('action', 'Page2.php?id=' + id);
Get this variable in PHP (obviously you might wanna do more checks on it)
<? $id = $_GET['id'] ?>
We can now use $id anywhere in our PHP and we'll be using the ID generated from JS. Neat, right? What if we want it in JS again though? Simply add another script tag and echo it there!
<script type="text/javascript">
var id = <? echo $id ?>;
</script>
EDIT: Updated to add a little about how it works as you said you're not too sure about the transition between PHP and JS.
PHP runs on the server. It doesn't know much about the browser, and certainly doesn't know about JS. It runs everything and finishes executing before the web page is displayed. We can pass PHP variables to JS by creating script tags and creating a new javascript variable, echoing the PHP value.
JS (JavaScript) runs in the browser. It doesn't know about anything that happens on the server; all it knows about is the HTML file it is running in (hit CTRL+U to see raw HTML). As JS runs at a completely separate time to PHP there is no easy way to transfer variables (e.g. $phpVar = myJSVar). So, we have to use server methods like POST or GET.
We can create a GET or POST request in 2 main ways:
Using a form
Using an AJAX request
Forms work in the way I've outlined, or you can create a hidden field, set the value you want and then check for that. This involves redirecting to another page.
AJAX (Asynchronous Javascript And Xml) works slightly differently in that the user doesn't have to leave the page for the request to take place. I'll leave it to you to research how to actually program it (jQuery has a nice easy API for it!), but it basically works as a background request - an example would be displaying a loading spinner whilst loading order details from another page.
Hope this helps, let me know if something's not clear!

php javascript ajax passing variables from mysql form

I have a form that gets data from a database and displays the results as buttons with the appropriate names. When i add javascript onclick i can diaplay the data_id. This all works but i want to be able to save the data to the main page in a textfield but it doesnt show anything? What code do you need to see or is it because i am loading an external php file to load the data that it isnt posting it past. Its doing my head in, I will post what code you want, i already have but had no joy.
For instance if i have a textfield called 'testField1' in my main page and on the same page i am getting a list of data from forms and mysql and the end is kicking out
<input id="button1" type="button" value="<?php echo $product_name; ?>" onclick="display()">
I want it to diplay that data in the main page 'testfield1' using the script
<script>
function display()
{
document.getElementById("textField1").value = "$product_name";
}
</script>
the code online is www.cheekytransport.co.uk/show.php

How to get information from Javascript to MySQL database using PHP?

(NEWBIE ALERT)
Hello! I am working on developing a database that stores information that people enter onto these online surveys. I don't have experience with Javascript, but I have worked with PHP and MySQL before. I am currently stuck on how to store the data to the database. Here are a few things about the code:
The person that created the online surveys had the online surveys written in Javascript (saved as HTML files)
Each survey is written in a separate file
Each survey has multiple data to be stored
Every time the user hits the next button, it goes to another page of the survey
I've worked on a project similar to this before, but my forms were only a page, so whenever the user clicks the "Submit" button, I had it go to another webpage written in a separate PHP file (kind of like a "results" page).
WHAT I DON'T UNDERSTAND/NEED HELP ON:
How do I make this so that when the user hits the "Next" button, it not only goes to the next page (what it's doing right now), but also sends the info to be stored in the database?
These surveys should be filled by people on their own computers so the surveys are written in JS (client-side). The storing part should be written in PHP (server-side) and MySQL, correct? Does this mean that I have to create a separate PHP file to create the code for transferring the data to the database or can it all be done in the same file? (I would think that I would need to create a separate file, one for each survey.)
Here's a general structure of how the HTML file:
<!DOCTYPE html>
<html>
<head><link rel="stylesheet" type="text/css" href="survey.css">
<script>
function Q2(){
document.getElementById("Q").innerHTML = "does something...<button type='button' onclick='Q3()'>Next</button>";
function Q3(){
document.getElementById("Q").innerHTML = "does something...<button type='button' onclick='Q4()'>Next</button>";
function Q4(){
document.getElementById("Q").innerHTML = "does something...<button type='button' onclick='Q5()'>Next</button>";
//keeps going until the last question
</script>
</head>
<body>
<h1>Meeting 1</h1>
<p id="Q">Some text...<br><input type="text" name="tweet" style='height: 50px;width: 500px;'><br><br>
<button type="button" onclick="Q2()">Next</button>
</p>
</body>
</html>
I've done a bit of research and looked at a few textbooks. I think AJAX may be something that I need to use? But I'm not too sure. If possible, could someone explain to me what I should be doing? I would like to not only be able to find a solution for this, but understand it as well.
Thank you in advance!!
For sending data to a PHP page using JavaScript, I'd recommend using the jQuery framework, where you can do it in as simple a code as this:
function Q2(){
var tweet = $("input[name='tweet']").val();
$.post("your_receiving_page.php", { data : tweet }, function(response){ //POST to PHP page where $_POST["data"] is the tweet variable
//deal with PHP output here
console.log(response);
if(response=="success"){
//javascript code to go to next page etc.
}
}
}
That way, you make a PHP file called "your_receiving_page.php" (or whatever) and handle the posted data like so:
<?php
$tweet = $_POST["data"];
//do stuff with $tweet, e.g. put it in a database
//...
//then end the code with "success", which is what you're looking for in the JavaScript as a successful callback
exit("success");

Categories