John Seen
John Seen

Reputation: 731

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

});

Upvotes: 0

Views: 1607

Answers (2)

Pekka
Pekka

Reputation: 449415

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.

Upvotes: 1

Lakshman Kambam
Lakshman Kambam

Reputation: 1618

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>

Upvotes: 0

Related Questions