0

So I know there is a better way to do this, but I can't, for the life of me, wrap my head around callback functions.

Below is a general mock-up of my code, which is sharing a question title on facebook from a Q&A site.

$('.facebook-share').click(function() {
      var hrefOfQuestionClicked = getHREF();

      var questionNumber = getQuestionNumber(hrefOfQuestionClicked);

      getQuestionTitle(questionNumber, hrefOfQuestionClicked);
    }




    function getQuestionTitle(questionNumber, href) {
      //-------------------PHP CALL---------------------
      if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();

        else {
          // code for IE6, IE5
          xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }

       

        xmlhttp.onreadystatechange = function() {
          if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {

            facebookShareCallback(xmlhttp.responseText, href);

          }
        };
        xmlhttp.open("POST", "getQuestionTitle.php?questionID=" + questionNumber, true);
        xmlhttp.send();
        //-------------------PHP CALL--------------------- 

      }


      function facebookShareCallback(questionTitle, href) {

        FB.ui({
          method: 'feed',
          link: href,
          name: questionTitle,
          picture: 'https://example.com/mypicture.jpg',
          description: ' ',
          caption: 'A question from my site.',
        }, function(response) {});
      }

It took me a long time just to figure out how to post a URL to facebook with a picture and caption. So, it is working at this point...BUT, once the new window opens to share to facebook, there is a considerable delay (maybe 8 seconds) on loading the facebook post module...Also, I'm pretty sure I can use a callback function to speed up this process and make it more efficient. Any advice or information is much appreciated! Thanks in advance! (There are some great answers referencing callbacks on Stack Overflow, but most are dealing with JSON and not a httprequest, and I couldn't seem to integrate the same strategy.)

programmingmusic
  • 429
  • 1
  • 3
  • 13
  • My secondary problem is, not knowing how to access the contents of xmlhttp.responseText, outside the scope of the onreadystatefunction. My current solution is not very modular, and I believe this, along with the load-time issue, can be fixed using callbacks. – programmingmusic Feb 18 '16 at 17:22
  • I am also going to want to use the function getQuestionTitle for use with linkedin and twitter sharing, so I don't really want to call facebookShareCallback() inside this function. PS. Even though I included callback in the function name, I'm not sure if this is actually a callback. – programmingmusic Feb 18 '16 at 17:41

0 Answers0