How to make jQuery ajax req with optional parameters [ solved with $.extend() ]

How to make jQuery ajax req with optional parameters [ solved with $.extend() ]
0

#1

Hi there,

I have two ajax requests that are very similar except for one key/value – I’m wondering how i can extract it out into a function and pass in the key / value for one request and leave it out for the other.

In my code below, the top function doesn’t have a token, where the bottom function does have a token. How can I set it up so I pass the token in when required, but leave it out when not required?
All the other values are the same, hence why I want to refactor
Here is my code:

var AjaxRequests = (function () {
            
            return {
              searchEntireChannel: function() {
                AjaxRequests.channelRequest("https://www.googleapis.com/youtube/v3/search", {
                  part: 'snippet, id',
                  q: q,
                  channelId: 'UCLhwHoIKtoWBccOFPDmEFpQ',
                  maxResults: 12,
                  type: 'video',
                  key: '{KEY}'
                })
              },
              
              getNextPageItems: function() {
                // select next button
                var token = $('#next-button').data('token'),
                        q = $('#next-button').data('query');
                // Clear button HTML
                $('#buttons').html('');
                // Run Get request on API
                AjaxRequests.channelRequest("https://www.googleapis.com/youtube/v3/search", {
                  part: 'snippet, id',
                  pageToken: token,
                  q: q,
                  maxResults: 12,
                  channelId: 'UCLhwHoIKtoWBccOFPDmEFpQ',
                  type: 'video',
                  key: '{KEY}'
                })
              },

              channelRequest: function(url, args) {
                $.get(url, args, function(data) { 
                  appendYouTubeData(data, q, function(item) { 
                    return item.id.videoId; 
                  });
                });
              }
            };
            
          })(); /* ------ AjaxRequests ---- */

Thank you in advance :slight_smile:


#2

Would something like this work? See my comment regarding the q variable that was shown in your original searchEntireChannel function.

var AjaxRequests = (function() {
  return {
    searchChannel: function() {
      var options = {
          part: "snippet, id",
          pageToken: token,
          q: q, // not sure where the value of q comes from in searchEntireChannel 
          maxResults: 12,
          channelId: "UCLhwHoIKtoWBccOFPDmEFpQ",
          type: "video",
          key: "{KEY}"
        }
      // select next button
      var token = $("#next-button").data("token") || null
      // , q = $("#next-button").data("query") || q;  see comment above
      if (token) {
        options.pageToken = token;
      }
      // Clear button HTML
      $("#buttons").html("");
      // Run Get request on API
      AjaxRequests.channelRequest(
        "https://www.googleapis.com/youtube/v3/search", options);
    },

    channelRequest: function(url, args) {
      $.get(url, args, function(data) {
        appendYouTubeData(data, q, function(item) {
          return item.id.videoId;
        });
      });
    }
  };
})(); /* ------ AjaxRequests ---- */


#3

Hey thanks for the response, I think that might work but I’m not sure… Its a bit complicated, but I think I have the answer, using the jQuery $.extends() method.

This seems to work well:

var AjaxRequests = (function () {
            
            var options = {
                part: 'snippet, id',
                maxResults: 9,
                type: 'video',
                key: 'AIzaSyDKJYxyWUDZhykA8DUVOorUbmC7J7QAAUg'
            }


            return {
              searchChannel: function() {
                // Get Form Input
                q = $('#query').val(); 
                createHTMLWrapper(q);
                // Build ajax req.
                AjaxRequests.channelRequest("https://www.googleapis.com/youtube/v3/search", 
                  $.extend({}, options, { 
                    q: q,
                    channelId: 'UCLhwHoIKtoWBccOFPDmEFpQ' 
                  })
                );
              }