Use ajax to send image file to python (flask) - javascript

I have an image on my website being updated every 5 seconds (using PubNub and a Raspberry Pi. I use JavaScript to update the image source). This works fine. My problem is I am trying to use Ajax to send the source file to python (flask) and store that file in a MySQL database. Then I want to display the file name on the website. I am new to java script/ ajax.
Here is my java script:
<script type=text/javascript>
$(function() {
$('img#imageid').bind( function() {
$.getJSON('/_button', {
proglang: document.getElementById('imageid').src,
}, function(data) {
$("#buttonState").text(data.result);
});
});
});
</script>
The img#imageid is the id of the current image and the #buttonstate is where i would like to have the image file name displayed
Here is my html:
<img id="imageid" src="http://searchengineland.com/figz/wp-content/seloads/2015/12/google-amp-fast-speed-travel-ss-1920-800x450.jpg">
<form>
<p>The button is <span id="buttonState"></span></p>
<br>
</form>
I do not want to use GET or POST. I would like to to automatically send to the python file every time the image source changes.
Here is my Flask view:
#app.route("/_button")
def _button():
try:
lang = request.args.get('proglang')
c.execute ("""UPDATE pictures SET file_name=%s WHERE user_id=%s""",
(str(lang), str(session['user_id'])))
return jsonify(buttonState=lang)
except Exception as e:
return render_template("500.html", error = str(e))

Related

Javascript to execute after python function in Flask

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
})
}

How I can append "PHP echo" code in html <div>

I am developing a chat between 2 users. I store the messages in a MySQL database and on chat box page I call AJAX each 2 seconds to get new messages.
All works fine with plain text messages but now I need to allow users to send also files.
I append the new messages using:
$("#chat_container").append(`
<div class="message-bubble ${clasa} ">
<div class="message-bubble-inner">
<div class="message-text">${output_response.Result[i].out_Message}</div>
</div>
<div class="clearfix"></div>
</div>
`);
My chat_container is:
<div id = "chat_container" class="message-content-inner">
</div>
${output_response.Result[i].out_Message} is the plain text that I store in mysql databased. For files I am uploading them to server using a php script that returns me the path and then i store the path as a message in database like:
<a href='upload/1619779744.jpg'>Picture</a>
Because of this the user will see that the message is actually a link and when he clicks on it he goes to
https://server/upload/1619779744.jpg and he downloads the picture which is good.
The problem is that I want to add some security to the site and not show direct path to files in link.
For this I implemented this class https://github.com/sujeetkrsingh/Secure-Download-Url
It works good in a separated file using:
<div class="message-text">AWS11 Logo</div>
This will return to user the link https://server.com/download.php?f=2f4df28349d56457b897f2ed3966799735564add3bef41c0 which hides the actual path of the file.
The problem is that if I store in database AWS11 Logo instead of <a href='upload/1619779744.jpg'>Picture</a> the link of the file is
https://server/%3C?php%20echo%20$encrypturl-%3EgetDownloadLink(%27upload/1619779744.jpg%27);%20?%3E which is wrong.
So the question is how I can append HTML + PHP code using jquery append function?
In my chat file I included the class in the beginning of file using <?php require_once("EncryptUrl.php"); $encrypturl=new EncryptUrl(); ?> and I renamed the file from .html to .php

Jquery $.post html to external php and print the html as pdf. Need to find optimal solution

I get mysql data.
Create - echo the mysql data as html.
If visitor wants to print the data as pdf (i mean to create pdf file and save on computer), i with jquery take the data and send to external php file. In the external php file, using http://www.tcpdf.org solution i want to create pdf file (on fly, only as variable; i do not want to save the file on my server) so that user can save it.
User remains on the same url, just after user clicks button, i offer the user to save rendered pdf. I do not want to change url or add html content to the url (like print_pdf.php?html_content).
At the moment i use code like below.
<div id="to_print_as_pdf">
<div>Some content from mysql</div>
<table>Another content from mysql</table>
</div>
<button type="button">Click to print as pdf</button>
<span id="result_print_pdf"></span>
Jquery to send the data
<script>
$("button").click(function(){
$.post('_prepare_to_print_pdf.php',
{ content_to_print: $('#to_print_as_pdf').html() },
function(result_print_pdf) {
$('#result_print_pdf').html(result_print_pdf).css('color', 'black');
});
});
</script>
File _prepare_to_print_pdf.php
$_SESSION['content_to_print'] = trim($_POST['content_to_print']);
<script>
window.location.href = "https://www.example.com/_print_pdf.php";
</script>
File _print_pdf.php
//Use http://www.tcpdf.org solution
$html = $_SESSION['content_to_print'];
$pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true);
$pdf->Output('example_001.pdf', 'I');
How to do the same without _prepare_to_print_pdf.php? Above solution waste server resources (creating session).
I tried with $.post to send html content directly to _print_pdf.php, but in such case instead of prompting to to save pdf file, i see "garbage" characters...
Solution at the moment
May be will help to someone
$('#for_hidden_form_for_print_pdf').append('<form action="_print_pdf.php" method="post" target="_blank" id="hidden_form_for_print_pdf">' +
'<textarea id="content_to_print" name="content_to_print">html content to send </textarea>' +
'<div><button style="display: none;" id="btn_to_print_pdf">Print pdf</button></div></form>');
$('#btn_to_print_pdf').trigger('click');
$( "#hidden_form_for_print_pdf" ).remove();
So when visitor clicks button/icon, i take necessary html data, insert into textarea id="content_to_print". Then trigger click for btn_to_print_pdf, then remove appended form. So i send to external php file, necessary html code. In php file i process the html code, create content for pdf file and print.

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");

Sails.js file upload - destroying req.body and .upload() callback executing before upload is actually complete

I am building a website using Sails, a page of which contains a form. This form has multiple text inputs, and a file upload input for the user to upload an image. The information from all text inputs are stored in a Postgres database, and the image is uploaded using the .upload() function described in the sails docs here and converted to a data uri which is then stored in the same Postgres database and used to display the image on the site.
The file input is the third to last input on the page, and I noticed that two things were happening:
1) The text in the two inputs after the file input was not being passed through to the controller as part of req.body, as form inputs normally are.
2) No data uri was stored in the database for some images.
I created a new basic sails app with a form that allows you to upload an image and exactly the same thing happens here.
Upon testing I discovered that small images work fine, while larger images do not. The 'small' image I used was 66kb, while another 800kb image produced the same effects mentioned above.
The new sails app, in the callback to the .upload() function, res.views another page that simply displays the uploaded image. With the 800kb image and larger images, by the time the page was rendered, instead of displaying the uploaded image, it displayed a broken image. In the chrome dev console it gave a 404 error for the image link, but if I add a query to the end of the image url (i.e. make chrome think it's a different url so reload the same image), the image displays fine. From this I am guessing that the .upload() callback is being called before the image is actually finished uploading, and by the time I have reloaded the image it has finished uploading.
I can see in the request headers that the inputs after the file input are being sent, but doing console.log(req.body) in the controller only logs out the inputs placed before the file input in the form.
I am using sails v0.11.0, and the code I am using is as follows:
HTML form (index.ejs)
<h1>Image Upload Test</h1>
<form method="post" enctype="multipart/form-data" action="/submit">
<div>
<input type="text" name="firstInput">
</div>
<div>
<input type="file" name="image">
</div>
<div>
<input type="text" name="imageUploaded" value="false">
</div>
<div>
<input type="hidden" name="test" value="hello!">
</div>
<button type="submit">Upload</button>
<script type="text/javascript">
$('input:file').change(function() {
$('input[name=imageUploaded]').val('true')
});
</script>
</form>
config/routes.js
module.exports.routes = {
'/': 'ImageController.show',
'/submit': 'ImageController.create'
The controller (ImageController.js)
module.exports = {
show: function(req, res) {
res.view('index.ejs');
},
create: function(req, res) {
var fileName = 'image' + Date.now() + '.jpg';
req.file('image')
.upload({saveAs: __dirname + '/../../assets/images/' + fileName}, function(err, uploadedFiles) {
if (err) return res.serverError(err);
console.log('file uploaded');
console.log();
console.log(req.body);
res.view('uploadedImage', {fileName: fileName});
});
}
};
The page to display the uploaded image (uploadedImage.ejs)
<%if (typeof(fileName) !== 'undefined') {%>
<a href="/">
<img src="/images/<%=fileName%>" style="width:100%; height:100%;">
</a>
<%}%>
Can anyone explain why this is happening and help me to fix it?
Thanks
As per sails file upload documentation, All the text fields must be uploaded before file field, otherwise they dont get passed to action.
Sails documentation File Upload sails

Categories