0

I'm currently making a project which requires ajax calls and I have made a function which triggers the AJAX in a single line. The callback functions are defined inside the $(document).ready() scope. I tried defining the scope in the start of $(document).ready() but I still get undefined from typeof fn.

$(document).ready(function() {
   let scope = this;

   function test(recvData) {
      alert("IT WORKS!")
   }

   function triggerAjaxDirectInterface(data, async, callback, extra_input) {
      console.log(callback)
      $.ajax({
         data: {
            command: data,
            scoutId: ScoutGlobals.bridgedId
         },
         type: 'POST',
         async: async,
         url: '/direct_process',
         success: function(recvData) {
            if (typeof callback !== "string") {
               if (extra_input !== undefined) {
                  callback(recvData, extra_input);
               } else {
                  callback(recvData);
               }
            } else {
               if (extra_input !== undefined) {
                  let fn = scope["test"];
                  console.log(typeof fn
                     if (typeof fn === "function") 
                        fn(recvData, extra_input);
                  }
                  else {
                     let fn = scope["test"];
                     console.log(typeof fn)
                     if (typeof fn === "function") 
                        fn(recvData);
                  }
               }
            }
         }
      });
   }
});

Zuckerberg
  • 1,781
  • 2
  • 10
  • 19
  • 1
    You are confusing scope and context. To access `test` you just need to call `test()`. `this.test` or `scope.test` are completely different things. And the `this` keyword denotes *context*, not scope. – VLAZ Apr 28 '20 at 06:28
  • Your brackets aren't balanced. – Barmar Apr 28 '20 at 06:29
  • @VLAZ, I need to call the function as a string so I do not think I am able to do test(). How should I go about calling the function from a string? Thanks for such a quick answer btw – Anirudha Saraf Apr 28 '20 at 06:30
  • 1
    you should create an object whose key is the function name, then you can use `object["test"]` – Barmar Apr 28 '20 at 06:32
  • @Barmar, thanks, I think i'll use that. – Anirudha Saraf Apr 28 '20 at 06:36
  • you shouldn´t check if callback is not a string but rather whether it is a function. – ItsFlo Apr 28 '20 at 06:41

0 Answers0