Search code examples
javascriptphpcallbackxmlhttprequest

How to implement different behavior for function in anonymous function javascript


I am new to JavaScript and I want to use send_request function twice, but with different behaviour. Element with name button1 should show response on the element, whereas button2 not.

  function send_request(url) {
    var xhr = new XMLHttpRequest();
    xhr.open('POST', url, true);
    xhr.send('data=test');
    xhr.onload = function () {document.getElementById('reply').innerHTML = xhr.responseText;};
  }
  document.getElementById('button1').addEventListener('click', function() { send_request("/data.php"); });
  document.getElementById('button2').addEventListener('click', function() { send_request("/clear_data.php"); });

Is it possible?


Solution

  • You could give send_request another parameter, a function that's called with the responseText, so you could pass one function that assigns to reply, and another function that does whatever you want instead:

    function send_request(url, callback) {
      var xhr = new XMLHttpRequest();
      xhr.open('POST', url, true);
      xhr.send('data=test');
      xhr.onload = () => callback(xhr.responseText);
    }
    document.getElementById('button1').addEventListener('click', function() {
      send_request("/data.php", (responseText) => {
        document.getElementById('reply').innerHTML = responseText;
      });
    });
    document.getElementById('bitton2').addEventListener('click', function() {
      send_request("/clear_data.php", (responseText) => {
        console.log('bitton 2 response: ' + responseText);
      });
    });