How to display image in HTML Page - javascript

I have a simple HTML page with a Button. Onclick it should show an image through an Ajax call.
It works fine in Postman Rest Client.
But in browser it is showing raw data instead of pic.
HTML
<html>
<button type="button" id="test" onclick="asset();"> Show Asset </button>
<div class="result"></div>
</html>
Ajax
$("#test").on("click", function asset() {
$.ajax({
type: 'GET',
url: 'https://url', //get an image
//url: 'https://url', //get audio file
beforeSend: function(xhr) {
xhr.setRequestHeader('Accept', 'image/png');
//xhr.setRequestHeader('Accept', 'audio/x-wav');
},
success: function(data) {
$(".result").html(data);
},
error: function(e) {
alert("error post" + JSON.stringify(e));
}
});
});
Sample Raw data -
�PNG IHDR�O^�fsRGB���gAMA���a pHYs���o�d�mIDATx^��{TUG����3���%c�N�8������N'��;Iw'�yu�_�Q�((�����(�E#T#��%B$$�ݝd�����I�$w�xn��3�[_�9ך�Zk��^��Wc
What should I do to get image?
Question 2.
How to display/play an audio/video in html page? As of now when I use another audio url...nothing gets disaplyed in browser.
---edit---
#Everyone thank you for your quick solutions.
Actually I also need to send an HTTP Header along with the URL.
Because the URL may give me an Image/Audio/Video file depending on the Request Header.
In this case how can I display Image/Audio/Video within Webpage?

If your url is just a link to image then no need to make an ajax call. Just add a img tag to your html and modify its src attribute value.
var url = "https://placehold.it/350x150"; // some url
$(function(){
$("#test").click(function(){
$("#imgId").attr("src",url);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<button type="button" id="test"> Show Asset </button>
<div class="result">
<img id="imgId" src="" />
</div>
</html>

You don't need to use ajax to load images, images are already loaded asynchronously. So just create an img element and add the src of the image. This works even when the page has been loaded.
$("#test").click(function() {
$(".result").append("<img src='img/src.png' />");
});

I think the data in success is a base64 encoded image. In that case you have to show it like:
success: function(data) {
document.getElementById('img').setAttribute( 'src', data );
}

Maybe image that is returned from api is base64 format. So you must convert that base64 data into image. Change your success callback like the following.
success: function(data) {
var img= new Image();
img.src = 'data:image/png;base64,'+ data;
$(".result").appendChild(img);
}

Related

not able to execute script for limited time

I have the following script which displays a loader when a file is uploaded using upload input. I want that loader should appear till the time file uploads and also wish to capture the name of the file. Can anyone please tell how this can be done
<input type="file" id="photoimg" name="file" />
<div id='preview' align="center"></div>
<script type="text/javascript" >
$(document).ready(function() {
$('#photoimg').change(function(){
$("#preview").html('');
$("#preview").html('<img src=img/loader.gif" alt="Uploading...."/>');
$("#imageform").ajaxForm({
target: '#preview'
});
});
});
</script>
You can use ajax call for this once you click the upload button you can show loader image and on the success, you can hide it and if the upload fails you can show the separate image for that.
$.ajax({
url: 'YOUR API PATH',
"Show the loader once the ajax call made using .show() or similar"
error: function() {
"show the error image using .show() or similar"
},
success: function(data) {
"Hide the loader on success"
},
type: 'POST'
});

How to display image with HTTP header in HTML page?

I have a basic HTML page with one button. On click of that button it should invoke an HTTP URL(with Accept header) on GET request.
The output of HTTP URL is a image or audio or video(as per the request header).
How should I write a Javascript or Ajax call
<html>
<form>
<input type="submit" id='img_display' onClick=imgDisp()>
<div id='display'></div>
</form>
</html>
Ajax code-
$("#img_display").on( "click", function imgDisp() {
$.ajax(
{
type: 'GET',
url: 'http_url',
dataType: 'json',
beforeSend : function(xhr)
{
xhr.setRequestHeader('Accept', 'image/png');
},
success: function(data){
alert("successfully")
},
error: function(e){
alert("error post" + e);
}
}
);
});
To make an Ajax request that returns either an image, audio, or video content, and forcing the receiving Javascript to guess the content type of a potentially huge blob of data, is poor design.
Depending on what type the audio and video content is, it may not be possible at all to do things that way.
It's much better to make one Ajax request that, say, returns a JSON object with the content type and URL:
{ "type": "image",
"url": "http://example.com/images/5/example.jpg" }
or, for a video:
{ "type": "video",
"url": "http://example.com/videos/5/example.mp4" }
You get the drift.
You can then handle the content appropriately, for example create an img element and set the src property to the URL, or invoke a video or audio player with the video URL.
This way, you can also send along other metadata that is relevant to rendering the end result - image dimensions and alt text, for example.
hope this will help you!!
$(document).ready(function(){
$("#Submit").click(function(){
var image_url = $(".imageurl").val();
$(".ImageContainer").html("<img src='"+image_url+"' width='200'>");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="imageurl">
<button id="Submit">Submit</button>
<div class="ImageContainer">
<!--Image Display -->
</div>

Call php file which return PDF with jQuery AJAX function

My php file: example_061.php create PDF return and everything works fine.
Now I want to call that file with jQuery AJAX to get this at my screen and I try:
$("#proba").click(function() {
//in here we can do the ajax after validating the field isn't empty.
$.ajax({
url: "tcpdf/examples/example_061.php",
type: "POST",
async: true,
data: {
ime: $("#ime").val(),
pozicija: $("#pozicija").val(),
jmbg: $("#jmbg").val()
}, //your form data to post goes here as a json object
dataType: "html",
success: function(response) {
window.open('example_061.pdf');
},
});
});
Everything is fine so success function work an I get alert message but I don't get PDF file as download or at screen. How I can do that?
You do not need to use AJAX to download a file. If the content-disposition header is set, it will be downloaded and the current page will not be reloaded.
Just add this to your php script that creates the PDF:
header('Content-Disposition: attachment; filename=' . $MyFileName);
And instead of AJAX, use a regular anchor tag link:
Download
As someone noted in the comments, if you need to post you can still use a simple form with the same effect:
<form method="POST" ACTION="tcpdf/examples/example_061.php">
<input type="hidden" name="myPostItem" value="My POSt VALUE" />
<input type="submit" value="download">
</form>

HTML button to load data and refresh UI

Here the situation:
In my html page I have a link, which onclick runs a PHP script.
<iframe style="display:none;" name="target"></iframe>
Load new tasks
I use an invisible iframe to execute the script but I stay on the same page.
This link executes script.php which updates mysql database, but in order to see new content the page must be reloaded.
Of course I can always create a separate button/link that reloads current page.
But I wonder if there is a way to execute the PHP script and reload current page with one html button.
Better use it this way:
1: Use a common Javascript Framework, for example JQuery
2: Create your Link and a Div for your Content:
Update my Data and reload my new Content
<div id="result"></div>
3: Use Jquery to add the click event to your link:
$('#reload').click(function(e) {
// Prevent from going to the link provided in href
e.preventDefault();
// make POST Request to script
$.post( "myScriptHandler.php", { value1: "1", value2: "2" })
.done(function( data ) {
// if done, refresh my Div with html content from your PHP Script
$('#result').html('')
$('#result').load('mydata.php');
});
}
You don't need AJAx - just return a script into the iframe which updates the toplevel page...
<?php
....
$new=run_updates();
print "<div id='newcontent'>$new</div>\n";
?>
<script>
var dest=parent.document.getElementById('oldcontent');
var src=document.getElementById('newcontent');
dest.innerHTML=src.innerHTML;
</script>
(not tested, YMMV)
I show you how to use Ajax in this case:
here is your html and js code:
<script type="text/javascript">
$(".link").on("click", function() {
$.ajax({
url: "your_php_script.php",
dataType: "json",
cache: false,
success: function(data) {
location.reload(true);
}
});
});
</script>
<html>
<body>
<a class="link" target="target">Load new tasks</a>
</body>
</html>
When you click the 'a' tag, the jQuery Ajax script call your php script, and when it return with success, then your page will be refresh.

loading content from php file with jQuery

The following code fetch all data (by clicking a.info link) from a php file "info.php" and prints in the #content div. The problem is that it prints everything from info.php file. Can I possibly select only some part of data from info.php file to load in #content?
The reason to ask this question is that, I want to load different data from the same php file for the different links.
$("a.info").click(function(){
var id=$(this).attr("id");
$("#box").slideDown("slow");
$.ajax({
type: "POST",
data: "id="+$(this).attr("id"),
url: "info.php",
success: function(html){
$("#content").html(html);
}
});
});
Html where content is loading:
<div id="box">
<div id="content"></div>
</div>
info.php
paragraph1.
paragraph2.
For example, In the above info.php file, i only want to load paragraph1 in the #content.
I hope my question is clear. Any help will be appreciated.
Assuming paragraph1 is a div element, change accordingly:
success: function(html){
var p1 = $(html).find("div#paragraph1");
$("#content").html(p1);
}

Categories