• Ajax technology – fetching data from server

    Published on May 7, 2009
    With 1 comment

    Connecting to the server

    In this example, we’re using the GET method, so we call the XMLHttpRequest object’s send method, passing it a value of null, which is JavaScript’s placeholder for a value of nothing.

    The JavaScript code will be:

    At this point we have created the XMLHttpRequest object, we opened it and we have created the connection to the server. From now we can make useful XML to store data and to have the source for our Ajax requests.

    Using Ajax with XML

    In the Firefox/Mozilla brand of browsers, we have to specify that we’re going to be downloading XML data, not plain text. To do that, we have to set the MIME type of the download to text/xml. We can achieve this using this line of code:

    Another difference will be that we will use the XMLHttpRequest object’s responseXML property, which holds a JavaScript XML document object:

    Let’s say that we want to download data regarding streets name from a certain city area (Bucharest in my case). For this we have to create a variable streetsName which will hold the data parsed from the XML file ruled by the Tag Name read-only property:

    After this we need to create the format for the placeholder of the data. In this case I will create a list of elements <span> displayed as block. Maybe it will be better to generate elements of an unordered list, but the problem is that, using the following sequence of JavaScript code, the HTML output will be a type of <ul></ul><li>...</li>, which means that we have an empty ul element and some orphans li elements, and this could lead to problems on CSS formatting.

    The necessary code will be:

    where obj = document.getElementById(divID); which is the container of our data.

    The structure of the XML file will be simple:

    From now the only thing we need to create is a form element which, based on user click action, will execute the function that will fetch the desired data from server.

    The entire code (HTML and JavaScript) can be downloaded from the following link, a simple example on how data is fetched form server using Ajax and XML.

    1 comment to "Ajax technology – fetching data from server"

    Share your thoughts on this article.

    Your email address will not be published. Required fields are marked *

    You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>