Display image from backend on frontend (Flask on backend, JS frontend) - javascript

I have web application that getting image (BLOB file in SQL) and needs to show it on web page.
Here is full code of page. 1) form to submit request 2) JS to make request 3) JS code to catch response and show it in
<img id="image_data" src="">
here is info from developer mode so i see image there in preview (and nothing in response)
enter image description here
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="{{ url_for('static', filename= 'css/style.css') }}">
<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon">
<title>Lazy board</title>
</head>
<script>
function addNavBar() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("navbar").innerHTML = this.responseText;
}
};
xhttp.open("GET", "navbar.html", true);
xhttp.send();
}
</script>
<body>
<div id="navbar"></div>
<script>
addNavBar();
</script>
<h1>Get picture</h1>
<form id="getPicture">
<label for="content_id">Content ID:</label>
<br><br>
<input type="text" id="content_id" name="content_id">
<br>
<img id="image_data" src="">
<br>
<input type="submit" class="button" value="Submit">
</form>
<script>
var form = document.getElementById('getPicture');
form.addEventListener('submit', function(event) {
event.preventDefault();
var contentId = document.getElementById('content_id').value;
var xhr = new XMLHttpRequest();
xhr.open('POST', '/getPicture');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.addEventListener('load', function() {
var response = xhr.response;
document.body.innerHTML += response;
document.getElementById('image_data').src = response;
});
var formData = new URLSearchParams();
formData.append('content_id', contentId);
xhr.send(formData);
});
</script>
</body>
</html>
Tried many things. backends response looks like that and yes, in DB is png file that i can view also
return Response(image_data, mimetype='image/png')

Related

Wondering why my XML URL Feed data is not displaying to HTML on the front-end. If I host the static XML in my directory, it works

Wondering why my XML URL Feed data is not displaying to HTML on the front-end. If I host the static XML in my directory, it works. However, when using a live feed from https://www.prlog.org/news/us/ind/sports/rss.xml, it does not work???
<!doctype html>
<html lang="en">
<head>
<title>Test XML Feed</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<div class="jumbotron jumbotron-fluid">
<div class="container">
<h1 class="display-8">Testing XML Feed</h1>
<hr class="my-2">
<div class="row">
<div class="col-12">
<div id="title"></div>
</div>
<div class="col-12">
<div id="description"></div>
</div>
</div>
</div>
</div>
<script>
//Display it
function displayFEED(i) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this, i);
}
};
//Call XML Feed with Live URL
xmlhttp.open("GET", 'https://www.prlog.org/news/us/ind/sports/rss.xml', true);
xmlhttp.send();
}
displayFEED(1);
// Call tag names from XML and match ID's
function myFunction(xml, i) {
var xmlDoc = xml.responseXML;
x = xmlDoc.getElementsByTagName("channel");
document.getElementById("title").innerHTML = x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue;
document.getElementById("description").innerHTML = x[i].getElementsByTagName("description")[0].childNodes[0].nodeValue;
}
</script>
</body>
</html>
If the server cooperates, your code using XMLHttpRequest can pull the remote resource; for the sample subdomain below I have configured the header and that way the code run here on stackoverflow.com can access the file fine:
const uri = 'https://cors-resources.liberty-development.net/sample1.xml';
const req = new XMLHttpRequest();
req.open('GET', uri);
req.onload = function(e) {
console.log(req.responseXML);
};
req.send();
But if the server does not cooperate you can't do anything but set up some kind of proxy service on your own site and have it pull the remote URIs with server-side code on your own site while client-side JavaScript simply connects to your own site.

XHR based ajax unable to upload files

I've a pretty simple javascript function which tries to send formdata along with an attached file to a php script. Below is my html and javascript code:
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery AJAX Submit Form</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
</head>
<body>
<form id="form" enctype="multipart/form-data">
<input type="text" name="name" id="name">
<input type="file" name="file" id="file">
<input type="button" onclick="upload()" value="Upload">
</form><span id="msg"></span>
<div id="result"></div>
<script type="text/javascript">
function upload(){
var formData = new FormData();
formData.append("file", document.getElementById("file").files[0]);
var xhttp = new XMLHttpRequest();
document.getElementById("msg").innerHTML = document.getElementById('file').files[0];
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200){
document.getElementById("msg").innerHTML = this.responseText;
}
};
xhttp.open("POST", "https://localhost/2.php");
xhttp.setRequestHeader("Content-type", "multipart/form-data");
xhttp.send(formData);
}
</script>
</body>
</html>
And below is my php script "2.php":
<?php
error_reporting(E_ALL);
$myfile = fopen("newfile.txt", "w");
fwrite($myfile, $_POST['name'].$_FILES['file']['name']);
fclose($myfile);
echo 'file written';
move_uploaded_file($_FILES['file']['tmp_name'],$_FILES['file']['name']);
echo "success";
?>
The above php script doesn't has any problem because it is able to retrieve the input text as $_POST['name'] and save it in the text file created. Also the script is successfully able to retrieve the file submitted and save it, only when I submit the html form normally without any javascript.
I want to submit both the input field data and selected file via XHR api only and not through fetch api.

Sending data from JavaScript to PHP via XMLHttpRequest

Good day.
I'm trying to send a simple piece of data from one php file (manage.php) to another (view.php).
I cannot send the data via a form, I want to send it via a JS script. Here's my attempt:
var read = function(id) {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "view.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("id=" + id);
}
In view.php, using $_POST["id"] causes an error stating that the index "id" is undefined.
What's the correct way to send the data? Thank you.
Your input is not complete. So I did the full example below that you can follow. I made a function, named readid(id), doing the same thing as you want. Then I call that function from html, when needed.
<!doctype html>
<html lang="fr">
<head>
<meta charset="iso-8859-1">
<title>Untitled Document</title>
<script type="text/javascript" charset="iso-8859-1">
function readid(id){
"use strict";
console.log("id=", id)
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "/cgi-bin/view.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function() {
if (this.readyState === 4 || this.status === 200){
console.log(this.responseText); // echo from php
}
};
xmlhttp.send("id=" + id);
}
</script>
</head>
<body>
<p>This is a test</p>
<input type="button" name="Submit" value="Submit" id="formsubmit" onClick="readid(id)">
</body>
</html>
view.php
<?php
$logFile = "view.log";
$id = $_POST['id'];
file_put_contents($logFile, $id);
echo $id;
?>
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<form id="formoid" title="" method="post">
<div>
<label class="title">First Name</label>
<input type="text" id="name" name="name" >
</div>
<div>
<label class="title">Name</label>
<input type="text" id="name2" name="name2" >
</div>
<div>
<input type="submit" id="submitButton" name="submitButton" value="Submit">
</div>
</form>
<script type='text/javascript'>
/* attach a submit handler to the form */
$("#formoid").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
$.ajax({
type: 'POST',
data: id,
url: 'PATH_TO_VIEW.PHP',
success: function(data) {
//do something
},
error: function(data){
console.log('Something went wrong.');
}
});
});
</script>
</body>
</html>
Now the data in ajax can be collected numerous e.g. serialized and new FormData(form) to quickly name two.

Upload Image using javascript in php

------------------- uploadimage.php file ------------
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<title>Upload Images</title>
<script>
/////This Function Show The Details OF Selected File
function fileselected()
{
var file=document.getElementById("photo").files[0];
document.getElementById("filename").innerHTML=file.name;
document.getElementById("filesize").innerHTML=file.size;
document.getElementById("filetype").innerHTML=file.type;
}
////////When Upload the image upload.php file is call but $_FILES is Empty
function uploadImage()
{
var fd=new FormData();
fd.append("photo",document.getElementById("photo").files[0]);
var xmlhttp = new XMLHttpRequest();
xmlhttp.upload.addEventListener("progress", uploadProgress, false);
var url = "http://localhost/JSONProgram/upload.php";
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("result").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST", url);
xmlhttp.setRequestHeader('Content-Type', 'image/png');
xmlhttp.send(fd);
}
function uploadProgress(evt) {
if (evt.lengthComputable) {
var percentComplete = Math.round(evt.loaded * 100 / evt.total);
document.getElementById('progressNumber').innerHTML = percentComplete.toString() + '%';
document.getElementById('prog').value = percentComplete;
}
else {
document.getElementById('progressNumber').innerHTML = 'unable to compute';
}
}
</script>
</head>
<body>
<form>
<div class="col-md-8">
<div id="result">Result Here</div>
<label for="photo">Select Image</label>
<input type="file" id="photo" name="photo" onchange="fileselected()"/>
<input type="button" value="Upload" onclick="uploadImage()" value="Upload"/>
<div id="filename"></div>
<div id="filesize"></div>
<div id="filetype"></div>
<div id="progressNumber">
</div>
<progress id="prog" value="0" max="100.0"></progress>
</div>
</form>
</body>
</html>
but in upload.php has empty array of $_FILES
<?php
print_r($_FILES);
?>
How To get File for Upload?
Please Help
Add the enctype attribute to your form tag like this:
<form enctype="multipart/form-data">
See this link for more information about the enctype.

AJAX Change HTML Content

I'm trying to change the content of a div with Ajax, however nothing happens... could someone help see what I'm doing wrong?
As far as i can see I'm not missing anything, but the buttons don't connect through. I am running XAMPP and apache is turned on.
Index Page
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta name="author" content="Malecia Legodi">
<meta name="description" content="Reload Website">
<script language="JavaScript" src="javascript.js"></script>
</head>
<body style="background-color:green">
<div>
<nav>
<table>
<tr>
<td>
<input type="button" id="home" value="Home"/>
</td>
<td>
<input type="button" id="contact" value="contact" />
</td>
</table>
</nav>
<section>
<div id="content" >
<h1>Content Review Summary</h1>
<p>
aaa...
</p>
<p>
bbb...
</p>
</div>
</section>
<footer align="center">© Reload Website</footer>
</div>
</body>
</html>
contact page:
<h1>Content Review Summary</h1>
<p>
ccc...
</p>
<p>
ddd...
</p>
Javascript.js
function initiate(){
content = document.getElementById('content');
var home = document.getElementById('home');
var contact = document.getElementById('contact');
home.addEventListener('click', readHome, false);
contact.addEventListener('click', readContact, false);
}
function readHome(){
var url = "home.html";
var request = new XMLHttpRequest();
request.addEventListener('load', showContent, false);
request.open("GET", url, true);
request.send();
}
function readContact(){
var url = "contact.html";
var request = new XMLHttpRequest();
request.addEventListener('load', showContent, false);
request.open("GET", url, true);
request.send();
}
//function showContent() to add data into your
function showContent(e){
//add data to secContent
content.innerHTML = e.target.responseText;
}
//use the listener to load your initiate() function
window.addEventListener('load', initiate, false);
change the div id content to secContent"
Also change:
content = document.getElementById('content');
to
content = document.getElementById('secContent');
As well as:
content.innerHTML = e.target.responseText;
to
secContent.innerHTML = e.target.responseText;
Your javascript's last couple of blocks of code are exactly alike to an example I was given at college (Although the example in question was only reading a single .txt file rather than several htmls it had the same problem) . I managed to get it to work by the method mentioned above. Hopefully it will help you as well.

Categories

Resources