1

In an HTML page, having two buttons (EDIT, DELETE), I do an AJAX call then I parse the returned JSON and I do perform an EDIT or a DELETE based on the returned ID. All this inside of a

$( document ).ready(function() {
    ...
    $('button.icons8.icons8-edit-file').on("click", function(){
        var key = $(this).attr('key');
        $.ajax({
            url: '/ede/' + key + '/json',
            method: 'POST',
            success: function (response) {
                // PARSING THE JSON, EXTRACTING THE ID FROM IT
                // AND PERFOMING THE EDIT
            }
        });
    })
    ...
    $('button.icons8.icons8-delete-file').on("click", function(){
        var key = $(this).attr('key');
        $.ajax({
            url: '/ede/' + key + '/json',
            method: 'POST',
            success: function (response) {
                // PARSING THE JSON, EXTRACTING THE ID FROM IT
                // AND PERFOMING THE DELETE
            }
        });
    })
    ...
});

What I would like to have is a global function what gets the key value, does the AJAX call and returns a value according to a pattern.

$( document ).ready(function() {
    ...
    $('button.icons8.icons8-edit-file').on("click", function(){
        var key = $(this).attr('key');
        var value = GLOBAL_FUNCTION(key, pattern_edit);
        // PERFOMING THE EDIT
    })
    ...
    $('button.icons8.icons8-delete-file').on("click", function(){
        var key = $(this).attr('key');
        var value = GLOBAL_FUNCTION(key, pattern_delete);
        // PERFOMING THE DELETE
    })
    ...
});

Where sould I put that GLOBAL_FUNCTION(p_key, p_pattern) fuction? Inside or outside of the ready function? How do I return the response from this global function? What if the result of parsing the response produces a list of values?

  • Useful reading: https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – freedomn-m Nov 13 '18 at 10:43

2 Answers2

2

Where should I put that GLOBAL_FUNCTION(p_key, p_pattern) function? Inside or outside of the ready function?

You can put it anywhere in scope of all the places you want to call it. Global is one possibility but should be avoided where possible. Instead, I'd suggest namespacing your common functions in to their own object. This way you can then extract them to a separate JS file for easy re-use.

How do I return the response from this global function?

If the function is making an AJAX request you can't return anything, as the call should be asynchronous. You can work around this by providing a callback function to execute when the request completes.

With those points in mind, the code would look something like this:

// common.js
var common = (function() { 
  return {
    global_function: function(key, callback) {
      $.get('/ede/' + key + '/json', function(response) {
        // perform common actions here, if needed..
        callback && callback(response);
      }
    }
  };  
})();

// in your page:
$('button.icons8.icons8-edit-file').on("click", function() {
    var key = $(this).data('key');
    common.global_function(key, function(response) {
      // Edit response.id...
    });
});

$('button.icons8.icons8-delete-file').on("click", function() {
    var key = $(this).data('key');
    common.global_function(key, function(response) {
      // Delete response.id...
    });
});

It would also make sense to extract the delete and edit logic to the common library, but I'll leave that to you based on your own logic.

Finally, note the use of data() here, as creating your own non-standard attributes will make your HTML invalid. Use data-key instead.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
0

You can put a function just in the jQuery ready state and use them in both callbacks. It's not really global, but it's in the right scope to use in both.

But GLOBAL_FUNCTION function can't return the value, because $.ajax is async. But you can pass a callback to the function, executed after finish.

And you can tell jQuery that the response is in JSON format, so it will parse it automatically for you.

$( document ).ready(function() {
    function GLOBAL_FUNCTION(key, type, callback) {
        $.ajax({
            url: '/ede/' + key + '/json',
            method: 'POST',
            dataType: 'json,
            success: function (response) {
                // EXTRACTING THE ID FROM RESPONSE 
                var id = response.id;
                
                if (type === 'edit') {
                  // PERFOMING THE EDIT
                }
                
                if (type === 'delte') {
                  // PERFOMING THE DELETE
                }
                
                // EXECUTE CALLBACK ON FINISH
                callback(id, type);
            }
        });
    };
    
    $('button.icons8.icons8-edit-file').on("click", function(){
        var key = $(this).attr('key');
        GLOBAL_FUNCTION(key, 'edit', (id, type) => {
            console.log(type + ' of id #' + id + ' finished');
        });
    })

    $('button.icons8.icons8-delete-file').on("click", function(){
        var key = $(this).attr('key');
        GLOBAL_FUNCTION(key, 'delete', (id, type) => {
            console.log(type + ' of id #' + id + ' finished');
        });
    })
    
});
eisbehr
  • 12,243
  • 7
  • 38
  • 63