How to display image with HTTP header in HTML page? - javascript

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>

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

setInterval to display div if ajax returns data

I'm trying to simulate a homemade push notification using setInterval but not sure how to do this. The ajax request works just fine at displaying messages. This is not the problem. I'm trying to display a separate notification in the section style='notification'.
Ajax snippet
setInterval(function(){
$.ajaxSetup({
cache:false,
type: "GET",
url: "log.php",
data: data,
});
$('#displayMessage').load('log.php');
//display div notification if return data
//document.getElementById('notification').style.display = 'block';
}, 3000);
markup
<section style='display:none;' id='notification' class="notif notif-notice alert alert-dismissable">
<h6 class="notif-title">Congratulations!
×
</h6>
<p>You have just received a new message</p>
</section>
Javascript's .load() method has an optional argument that is a function to do after the load is completed. It would look like this:
$('#displayMessage').load('log.php', function(){
$('#notification').show();
});

How to display image in HTML Page

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

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>

"Waiting for response" message when Ajax call

When I use Ajax call(jquery) in the HEAD section I find a "waiting for response message" on a chrome browser with revolving circle. I don't want this ugly look. Is there a way to avoiding this?
PS: When I use input tag to call the JavaScript(Ajax call) function like
<input id="launcher" type="button" onfocus="go()" value="Go!"></input>
I couldn't see a waiting circle. Cause my program should call the function automatically I couldn't use this method.(If I use document.getElementById("launcher").focus() to automatically start the function, It showed waiting circle again.) I guess there's a some different context to call JavaScript function.
Update Here is my sample code
<HEAD>
<SCRIPT TYPE="text/javascript">
function go() {
$.ajax({
url: "/myService",
success: function(data){
document.getElementById("result_area").innerHTML = data;
go();
}
});
}
$(document).ready(function(){
go() //Here I want to Comet call;
});
go(); //should start automatically.
</SCRIPT>
</HEAD>
<BODY>
<!-- <input id="launcher" type="button" onfocus="go()" value="Go!"></input>
This doesn't show the waiting circle. Why? Use different call context? -->
<div id="result_area"></div>
</BODY>
there are some issue i want to highlight
<input id="launcher" type="button" onfocus="go()" value="Go!"></input>
this should be
<input type="button" id="launcher" value="Go!" />
then
if u want a image instead of text then put a div before form with display:none
in ajax call you are not writing url link with extension (.php or .html or .js )
in success : you again calling go(), this smell like recursive function
what data u r sending to the server?? data: is missing from ajax option
also mention dataType ( optional)
if you dont want to run ajax automatically then do it on some event( like i do on click)
bind with the document ready
write javascript code in head ( best practice to write just before </body> )
i tried my hard to tell you the basic, here is my way
HTML
<div id="waiting" style="display: none;">
<img src="images/ajax-loader.gif" title="Loader" alt="Loader" />
</div>
<form>
// here is your form
</form>
jQuery
<SCRIPT TYPE="text/javascript">
$(document).ready(function(){
$('#waiting').show(500);
// instead run automatically now it will work on click of button
$('#launcher').click( function () {
$.ajax({
url: "/myService.html", // or whatever page
// by the way where is data which you sent on server??
data: { email : $('#email').val() }, // like i send the email to the serever
dataType : "json",
async : false,
success: function(data){
$('#waiting').hide();
$("#result_area").html(data);
}
});
});
})
I found that this waiting circle on XMLHttpRequest is depend on a browser implementation. On IE7, Firefox4 it didn't show any waiting circle or bar while chrome11, Windows safari had one.
I believe that standard on this should be made cause it impacts greatly on user experience.

Categories