Skip to content

April 21, 2009

Programmer’s Journal

Getting XML objects while using Mediawiki API + AJAX

Problem/Error: Trying to obtain a responseXML object from a Mediawiki API query results in a null pointer. A responseText object, however, returns the HTML text just fine.

Solution: What’s happening here is that Mediawiki API is responding to the AJAX request (GET or POST, it doesn’t matter) using the default format, namely, a plain text, HTML formatted version of the original XML. To obtain an XML object (or any other kind of object that Mediawiki knows, for that matter e.g. JSON), you have to explicitely tell the API in which format you require the answer. For example:

The following code shows a query requesting information about the main page of a mediawiki installation.

//JS method called from an "onClick" event
function getMainPageInfo()
{
   //start by getting an XMLHTTP object
   xmlHttp=GetXmlHttpObject();

   //make a simple check of AJAX support
   if (xmlHttp==null){
     alert ("Your browser does not support AJAX!");
     return;
   }

   //Modify the path with your own info
   var url="/mediawiki/api.php";
   var params="action=query&titles=Main%20Page&format=xml";

   //Send the proper header information along with the request
   xmlHttp.onreadystatechange=paintMediawikiAnswer;
   xmlHttp.open("POST", url, true);
   xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
   xmlHttp.setRequestHeader("Content-length", params.length);
   xmlHttp.setRequestHeader("Connection", "close");
   xmlHttp.send(params);
}

//Get the answer and paint it to a <span> element
function paintMediawikiAnswer()
{
   if (xmlHttp.readyState == 4) {
      //get the XML tree
      xmlDoc = xmlHttp.responseXML.documentElement;
      switch (xmlHttp.status) {
         // Page-not-found error
         case 404:
            alert('Error: Not Found. The requested URL could not be found.');
            break;
         default:
            // Call the desired result function
            elementRetrieved=xmlDoc.getElementsByTagName("page");
            alert("Pages received: "+elementRetrieved.length);
            break;
      }
   }
}
Read more from Programmer's Journal

Share your thoughts, post a comment.

(required)
(required)

Note: HTML is allowed. Your email address will never be published.

Subscribe to comments

Bad Behavior has blocked 177 access attempts in the last 7 days.