I have a somewhat expensive server-side operation that produces an image and some associated text metadata about that image. My web page will display both.
The image and its data are fetched with AJAX calls. On the server side, it is possible to produce the image and the metadata at the same time. How can I transfer (and display) both the image and the data with one AJAX call?
(The problem with making two calls is that the expensive server-side operation ends up happening twice when it doesn’t have to.)
Edit:
To clarify, the image is drawn dynamically in a servlet. If it has a separate URL from the metadata, then two requests are required, and the expensive operation happens twice. I don’t want to write my own caching in the servlet, since using a caching proxy and max-age is otherwise working great.
UPDATE 2:
If both processes share the same resource URL, you could send the metadata as custom HTTP headers. I’m not completely sure about the following technique though.
Anyway, even if the browser mechanism doesn’t work, at least there’s a chance for the caching proxy to cache a single response, instead of what would otherwise be two.
Also, although you said you don’t want to use base64 encoded images, there are techniques to determine whether a browser supports them or not. You may then use them for smart-enough browsers and sacrifice a double request for the others. At least is not that worse.
UPDATE 1 (no longer applies):
If you already rely on a caching proxy and the max-age header, then this is what I’d do:
OLD ANSWER (no longer applies):
I don’t really understand what you mean by “producing an image” but I’ll assume you just want to send an image URL back to the web page. In this case you could use JSON to send both the image URL and metadata. Like this:
You send this response as soon as the two server-side operations are done. You initiate both with a single Ajax request, and get the response for both image URL and metadata at once. Then, on the client-side you read them very easily:
The above would happen inside the onreadystatechange handler. If you’re using a library things will be a bit easier.