0

I am using the following AJAX call to generate search suggestions:

$(".smart-suggestions").load('id-get-data.php?searchword=' + self.value);

The search suggestions are returned into a 'div' based on the user's input. I was wondering if there is a way to 'clear' the data returned from ajax somehow using javascript, jquery or ajax? to erase the results returned.

AnchovyLegend
  • 12,139
  • 38
  • 147
  • 231

2 Answers2

2

If you use load you can append the time to "fool" the cache mechanism

$(".smart-suggestions").load('id-get-data.php?searchword=' + self.value +'&x=' +
    (+new Date()));
gdoron
  • 147,333
  • 58
  • 291
  • 367
  • Thank you, this seems like a simple solution. Can you please explain why/how this works? – AnchovyLegend Dec 15 '12 at 22:20
  • @MHZ, sure, it works because the browser now send a new request with different parameters so he can't use the cache. there is no way for the browser to know the TimeStamp isn't a real parameter, so... it works. – gdoron Dec 15 '12 at 22:21
  • In my example I am using AJAX to populate search suggestions when I user inputs text into an input field. The user can use more than one input field to generate search suggestions. Once the user generates search suggestions in input field A, then clicks on input field B, the results from input field A still appear for a couple of seconds before they are cleared out. Clearing the cache does not seem to solve this issue, however, any idea why this might be? – AnchovyLegend Dec 15 '12 at 22:31
  • @MHZ, sorry I need more context. – gdoron Dec 15 '12 at 22:36
  • Try to imagine two input fields, A and B. Input 'A' allows users to search for item id's using AJAX (as they type). Input 'B' allows users to search for item names using AJAX (as they type). When a user tries to search for an item number by inputting text into input A, then clicks on input B to try to search by item name by entering some text, the data generated by the first AJAX search (input A) still appears for some time before the product name search results are populated. – AnchovyLegend Dec 15 '12 at 22:43
1

You can send the request with $.ajax and just add cache: false to the options:

$.ajax({
    url: 'id-get-data.php',
    type: 'GET',
    data: {
        searchword: self.value
    },
    cache: false,
    success: function(data) {
        $('.smart-suggestions').html(data);
    }
});
Blender
  • 289,723
  • 53
  • 439
  • 496
  • The docs: _"If set to false, it will force requested pages not to be cached by the browser. Setting cache to false also appends a query string parameter, "_=[TIMESTAMP]", to the URL."_ (just like in my answer...) +1 – gdoron Dec 15 '12 at 22:18
  • @gdoron: Yep. I just thought it would be cleaner to URL encode `self.value`. – Blender Dec 15 '12 at 22:19