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.)