-2

Let's say I have a set of pre-loaded images on a web page. When selecting any image from the list, AJAX request is made to another service, which returns HTML payload with multiple HTML elements, related to the selected image. Once returned, HTML payload is placed underneath the selected div. I cannot change what and how this service returns the data.

I need to prevent the following: avoid doing AJAX request if image was already clicked(AJAX is already made for the image) by user during the one page load. Essentially, I want my ajax request to happen one time max for one image per one page load. Note: I cannot change the output of the service that I call with ajax. All I can is placing html response of ajax request into some div.

What are the common jquery/javascript solution for this kind of problem?

WomenWhoCode
  • 396
  • 1
  • 6
  • 18
  • 1
    *"I cannot change the output of the service that I call with ajax..."* aah I'm confused, do you still have the ability to add your `script`s ? If yes, consider including your attempt so far. – ThS Aug 05 '19 at 00:08
  • Could be as simple as adding a class to the image....or may need a cache object. Really not much detail provided. Show us what "selecting image" means and how the ajax gets associated to that and what persists in page between these selections – charlietfl Aug 05 '19 at 00:10
  • 2
    "cache" the result of each AJAX request in some variable that you can use to determine if you need to make the AJAX request again or not – Jaromanda X Aug 05 '19 at 00:10
  • This may be helpfull: https://stackoverflow.com/questions/17104265/caching-a-jquery-ajax-response-in-javascript-browser – François Huppé Aug 05 '19 at 00:12

1 Answers1

2

What you need to do is to create a function that stores the result of your AJAX request in an object, the key being the source of the request

You write the function in such a way that if this object has the requested key, the "cached" content is returned, otherwise an AJAX request is made, and the result is stored in the "object"

Given that AJAX is asynchronous, the easiest way to implement this is using Promises. That way you can store the Promise immediately in the "object" and return the Promise immediately. Since you can execute .then (or await) as many times as you like on a given Promise, this means that when you're calling your function that does the caching, you should expect a Promise returned, and use either .then (or await inside an async function) to properly access the result of the AJAX data

Jaromanda X
  • 53,868
  • 5
  • 73
  • 87