1

A bit of an advanced question here (for a noob like me haha). I am writing an app that makes AJAX requests when I click on a navigation item to show up content relevant for that navigation item. So far so good. One request per click, thats fine.

The problem arises when I make AJAX requests through the JS that is retrieved by the first AJAX request, the one from the navigation item. A sort of inception if you will. A request within a request o.O

The code I am presenting to you has the job of retrieving data when a key is up, after a specified delay. The problem is, that even though there is a delay, a request is made for every key pressed. How do I reduce the number of requests?

var delay = (function(){
      var timer = 0;
      return function(callback, ms){
        clearTimeout (timer);
        timer = setTimeout(callback, ms);
      };
    })();

$("#browse-foods-search-input").keyup(function(){
    delay(function(){ 

        // This IF checks if the field is empty. If so, the default content is loaded
        if ($("#browse-foods-search-input").val() == "")
        {
            $.ajax({
                type: "GET",
                url: "ajaxLoad.php?action=food-journal&mod=browse-foods&send_header=0",
                success: function(response) {
                    $(".browse-foods-container").html(response.html);
                    eval($(response.js).text());                           
                }
            });
        }
        else {    // This ELSE creates the request for searching
           $.ajax({
               type: "GET",
               url: "ajaxLoad.php?action=food-journal&mod=browse-foods&search_key="+$("#browse-foods-search-input").val(),
               success: function(response) {
                    $(".browse-foods-container").html(response.html);
                    eval($(response.js).text());
               }
             });   
        }   
    }, 500 );        
});  

Please note that the above code works as intended, but I am interested in optimizing my code. Any questions, comments, criticisism are welcome!

  • You could measure the time between calls and only do this every n milliseconds. Another approach would be to have your ajaxLoad.php set cache information which will tell your browser not to call that link too often. – Marged Dec 29 '15 at 01:12
  • i read about caching but have no idea how to implement this :( can you help me with that? – Mikołaj Marciniak Dec 29 '15 at 01:15
  • There will be many examples how to set http cache headers using php here on SO, I am sure you will find some using the search. But I think caching alone will not be the ideal solution because the cache is built per URL and you are dynamically changing the url in the `search_key` part. – Marged Dec 29 '15 at 01:17
  • okay. but how do i utilize this cache functionality? does it mean that the html content is downloaded for a specific keypress only once and then retrieved "locally" instead of through ajax? – Mikołaj Marciniak Dec 29 '15 at 01:18
  • The browser should cache automatically, since you're using `GET`. – Barmar Dec 29 '15 at 01:20
  • Use the Network tab of DevTools to see how often it's sending the requests. It looks like it should not be more than 2/second. – Barmar Dec 29 '15 at 01:21
  • Try to define an optimal value for your cache, because browsers tend to cache too long if you don't specify a value on your own. And then see this example: http://stackoverflow.com/questions/1620602/javascript-jquery-make-an-ajax-request-when-a-user-is-typing-in-a-textarea for – Marged Dec 29 '15 at 01:24
  • 1
    okay guys i checked with the network tab and the results are following: just to test things i pressed a left arrow once (to keep the search field empty for testing) and there was one request. i pressed it again, and there were two requests. i pressed again, four requests. again, 8 requests. its because i have ajax within ajax. but if i dont, some of my js doesnt work. why is that? – Mikołaj Marciniak Dec 29 '15 at 01:26

0 Answers0