Search code examples
javascriptfacebookfbjsfacebook-fql

Print data instead of alert


I use the javascript to get some data from facebook using javascript sdk:

window.fbAsyncInit = function() {
    FB.init({appId: '111164862286924', status: true, cookie: true,
             xfbml: true});
/****************************************/

FB.api('/f8', function(response) {
  alert(response.company_overview);
});

/****************************************/
  };
  (function() {
    var e = document.createElement('script'); e.async = true;
    e.src = document.location.protocol +
      '//connect.facebook.net/en_US/all.js';
    document.getElementById('fb-root').appendChild(e);
  }());

This code works fine but if I change alert with documen.write to print the data instead of showing it inside the popup window it doesn't seem to work any more. It doesn't print anything. Can anyone please tell what could be the reason?

Thanks in advance


Solution

  • You can't use document.write after the initial parse of the page is complete. Fortunately, though, there's no particular reason to.

    If you have an element on the page and you wish to append to it, you can do this:

    var parent = document.getElementById('theId');
    var p = document.createElement('p');
    p.innerHTML = "This is the <em>new content</em>.";
    parent.appendChild(p);
    

    Live example (It doesn't have to be an p element, it can be a div or span or anything else that's a valid child of the parent element.)

    Note that if you just want to append to the bottom of the document (relatively rare, but hey), you can just use document.body in place of parent:

    var p = document.createElement('p');
    p.innerHTML = "This is the new content.";
    document.body.appendChild(p);
    

    Similarly, if you want to replace the content of an element, just get a reference to it (using getElementById is a convenient way if the element has an ID, but there are other ways) and update it, rather than append to it:

    var target = document.getElementById('targetId');
    target.innerHTML = "This is the <em>updated content</em>.";
    

    More re document.write: document.write actually writes to the HTML stream being parsed by the HTML parser. Naturally, once the page rendering is complete, there's no longer an HTML stream being parsed. But the DOM methods above are available for manipulating content on the page after the page is rendered.


    Off-topic: DOM manipulation and DOM searching (finding elements to update) are both made easier (and in particular made easier cross-browser) if you use a library like jQuery, Prototype, YUI, Closure, or any of several others which will have syntactic sugar and workarounds for browser eccentricities, etc.