How to get image using ajax request?

There is a .php file that returns a .png image file.

How to get this image using jQuery $.ajax() ?

In addition, if there were errors with the input parameters, the .php file will return an error in the JSON path.

How to understand what information was returned - an image or JSON with an error?

UPDATE:

I need to make some statistics graphs using this script. .php file receives some data (for example, account identifier, what statistics is requested) and checks if this user (user identifier obtained from the session is allowed to view the requested user statistics or not). If it is allowed, than the image is returned, if not - than the json error. So what can I do, but if there is an error, the image does not load. But I need to show an error notification to the user.

+4
source share
3 answers

You can use it as follows:

 <img src="data:image/png;base64,R0lGODlhUA... " width="80" height="15" /> 

So, I suggest you get a base64 encoded string from an ajax request and use it to display the image

+2
source

If you return this image as an attachment to the response - I cannot get this attachment in the javascript variable, otherwise, if you return the image in the response stream and set the type of content content, you can simply assign you .php image srs :

 $('img').attr('src', 'my-image-handler.php'); 
+3
source

http://www.anthonymclin.com/code/7-miscellaneous/98-on-demand-image-loading-with-jquery

You need to send the image in the desired format to the AJAX request. The solutions are, for example, octect stream, base64, etc. There are many ways to achieve on-demand content downloads. It is important to maintain synchronization on the server side and on the client side.

It looks like if you send JSON to the server, return the XML, but expect the HTML you JS will not work.

+1
source

All Articles