Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 6 of 6
  1. #1
    New to the CF scene
    Join Date
    Oct 2012
    Posts
    7
    Thanks
    0
    Thanked 1 Time in 1 Post

    Using AJAX to read an XML file

    I am new to using AJAX and am struggling in make the following code work:

    Code:
    Core.sendRequest = function(url,callback,postData) {
    	//checks to see if we can create the XMLHttpObject
    	var req = Core.createXMLHttpObject();
    	
    	//if returns false cancel operation 
    	if (!req) return;
    	
    	//check to see if postData was passed if so set method to POST
    	var method = (postData) ? "POST" : "GET";
    	
    	//call the open method, send the method "POST" or "GET" and pass true
    	req.open(method,url,true);
    	
    	//set the request header
    	req.setRequestHeader('User-Agent','XMLHTTP/1.0');
    	
    	//if postData is sent then set request header for forms
    	if (postData)
    		req.setRequestHeader('Content-type','application/x-www-form-urlencoded');
    	//if everything returns ok send req value to "callback"
    	req.onreadystatechange = function () {
    		if (req.readyState !== 4) return;
    		if (req.status !== 200 && req.status !== 304) {
    			return;
    		}
    		callback(req);
    	}
    	// if we have already completed the request, stop the function so as not
      	// to send it again
    	if (req.readyState === 4) return;
    	
    	//if postdata was included send it to server side page. Information
    	//can be received by using $_POST['data'] (this is via PHP)
    	if (postData){
    		req.send("data="+postData);
    	}
    	else{
    		req.send(null);
    	}
    	
    }
    
    //depending on the browser return appropriate request.
    Core.XMLHttpFactories = [
    	function () {return new XMLHttpRequest()},
    	function () {return new ActiveXObject("Msxml2.XMLHTTP")},
    	function () {return new ActiveXObject("Msxml3.XMLHTTP")},
    	function () {return new ActiveXObject("Microsoft.XMLHTTP")}
    ];
    
    //This method cycles through all requests in XMLHttpFactories until
    //one is found.
    Core.createXMLHttpObject = function() {
    	var xmlhttp = false;
    	for (var i=0;i<Core.XMLHttpFactories.length;i++) {
    		try {
    			xmlhttp = Core.XMLHttpFactories[i]();
    		}
    		catch (e) {
    			continue;
    		}
    		break;
    	}
    	return xmlhttp;
    }
    Second js file:

    Code:
    
    var Core = {};
    
    // W3C DOM 2 Events Model
    if (document.addEventListener)
    {
    
    	Core.addEventListener = function(target, type, listener)
    	{
        	target.addEventListener(type, listener, false);
    	};
    	
    	Core.stopPropagation = function(event)
      	{
        	event.stopPropagation();
      	};
      	Core.preventDefault = function(event)
      	{
        	event.preventDefault();
      	};
    	Core.removeEventListener = function(target, type, listener)
      	{
        	target.removeEventListener(type, listener, false);
      	};
    
    }
    
    else if (document.attachEvent)
    {
      Core.addEventListener = function(target, type, listener)
      {
        // prevent adding the same listener twice, since DOM 2 Events ignores
        // duplicates like this
        if (Core._findListener(target, type, listener) != -1) return;
    
        // listener2 calls listener as a method of target in one of two ways,
        // depending on what this version of IE supports, and passes it the global
        // event object as an argument
        var listener2 = function()
        {
          var event = window.event;
    
          if (Function.prototype.call)
          {
            listener.call(target, event);
          }
          else
          {
            target._currentListener = listener;
            target._currentListener(event)
            target._currentListener = null;
          }
        };
    
        // add listener2 using IE's attachEvent method
        target.attachEvent("on" + type, listener2);
        
        //The above code allows us to create an event listener for IE
        //and be able to use the "this" keyword.  The code below stores 
        //our object references so the can be cleaned up later.  This 
        //stops any memory leak issues.
        
    
        // create an object describing this listener so we can clean it up later
        var listenerRecord =
        {
          target: target,
          type: type,
          listener: listener,
          listener2: listener2
        };
    
        // get a reference to the window object containing target
        var targetDocument = target.document || target;
        var targetWindow = targetDocument.parentWindow;
    
        // create a unique ID for this listener
        var listenerId = "l" + Core._listenerCounter++;
    
        // store a record of this listener in the window object
        if (!targetWindow._allListeners) targetWindow._allListeners = {};
        targetWindow._allListeners[listenerId] = listenerRecord;
    
        // store this listener's ID in target
        if (!target._listeners) target._listeners = [];
        target._listeners[target._listeners.length] = listenerId;
    
        // set up Core._removeAllListeners to clean up all listeners on unload
        if (!targetWindow._unloadListenerAdded)
        {
          targetWindow._unloadListenerAdded = true;
          targetWindow.attachEvent("onunload", Core._removeAllListeners);
        }
      };
      
    Core.stopPropagation = function(event)
      {
        event.cancelBubble = true;
      };
      
    Core.preventDefault = function(event)
      {
        event.returnValue = false;
      };
      
    Core.removeEventListener = function(target, type, listener)
      {
        // find out if the listener was actually added to target
        var listenerIndex = Core._findListener(target, type, listener);
        if (listenerIndex == -1) return;
    
        // get a reference to the window object containing target
        var targetDocument = target.document || target;
        var targetWindow = targetDocument.parentWindow;
    
       	// obtain the record of the listener from the window object
        var listenerId = target._listeners[listenerIndex];
        var listenerRecord = targetWindow._allListeners[listenerId];
    
        // remove the listener, and remove its ID from target
        target.detachEvent("on" + type, listenerRecord.listener2);
        target._listeners.splice(listenerIndex, 1);
    
        //remove the record of the listener from the window object
        delete targetWindow._allListeners[listenerId];
      };
        
    
    Core._findListener = function(target, type, listener)
      {
        // get the array of listener IDs added to target
        var listeners = target._listeners;
        if (!listeners) return -1;
    
        // get a reference to the window object containing target
        var targetDocument = target.document || target;
        var targetWindow = targetDocument.parentWindow;
    
        // searching backward (to speed up onunload processing), find the listener
        var len = listeners.length;
        for (var i = len - 1; i >= 0; i--)
        {
          // get the listener's ID from target
          var listenerId = listeners[i];
    
          // get the record of the listener from the window object
          var listenerRecord = targetWindow._allListeners[listenerId];
    
          // compare type and listener with the retrieved record
          if (listenerRecord.type == type && listenerRecord.listener == listener)
          {
            return i;
          }
        }
        return -1;
      };
    
      Core._removeAllListeners = function()
      {
        var targetWindow = this;
    	//this is a for loop going though an associative array
        for (id in targetWindow._allListeners)
        {
          var listenerRecord = targetWindow._allListeners[id];
          listenerRecord.target.detachEvent("on" + listenerRecord.type, listenerRecord.listener2);
          delete targetWindow._allListeners[id];
        }
      };
    
      Core._listenerCounter = 0;
    }//else if (document.attachEvent)
    The client would like it to read an XML file by using an input box to type in your query and display the results.

    The XML file is basic an I need to search it via the authors name. On some of them, there are two authors listed please let me know you canl I always want

  • #2
    Senior Coder
    Join Date
    Jan 2011
    Location
    Missouri
    Posts
    4,686
    Thanks
    25
    Thanked 656 Times in 655 Posts
    This will read an xml file for you and place it into a div. I know that's not what you want but it's a start. "xmlhttp.responseText" is the returned file and you can now do with it as you like. You need to post the xml file or if too long a good portion of it. And explain what the client wants by an example. And you need to explain what you want also.
    The javascript:
    Code:
    <script type="text/javascript">
    
    function loadXMLDoc(url)
    {
    var xmlhttp;
    var txt,xx,x,i;
    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)
        {
        document.getElementById('txtCDInfo').innerHTML = xmlhttp.responseText;
        }
      }
    xmlhttp.open("GET",url,true);
    xmlhttp.send('');
    }
    </script>
    
    <button onclick="loadXMLDoc('movies.xml');">PUSH</button><!--  PUT YOUR XML FILE NAME HERE-->
    <div id="txtCDInfo"></div>

  • #3
    New to the CF scene
    Join Date
    Oct 2012
    Posts
    7
    Thanks
    0
    Thanked 1 Time in 1 Post
    Here is the badly screen formatted XML file

    Code:
    <books><book><isbn>0-321-70095-3</isbn><title>The JavaScript Pocket Guide</title><authors><author>Lenny Burdette</author></authors><publisher>Peachpit Press</publisher></book><book><isbn>978-0-596-52068-7</isbn><title>Regular Expressions Cookbook</title><authors><author>Jan Goyuaerts</author><author>Steven Levithan</author></authors><publisher>Peachpit Press</publisher></book><book><isbn>978-0-596-00987-8</isbn><title>Web Design In A Nutshell (3rd Edition)</title><authors><author>Jenifer Niederst Robbins</author></authors><publisher>O'Reilly</publisher></book><book><isbn>978-0-596-00987-6</isbn><title>Web Design In A Nutshell (2nd Edition)</title><authors><author>Jenifer Niederst Robbins</author></authors><publisher>O'Reilly</publisher></book><book><isbn>978-1-4302-1011-5</isbn><title>PHP Object Oriented Solutions</title><authors><author>David Powers</author></authors><publisher>Friends of Ed</publisher></book><book><isbn>978-0-470-41396-8</isbn><title>Beginning PHP 5.3</title><authors><author>Matt Doyle</author></authors><publisher>Wrox</publisher></book><book><isbn>978-0-470-10263-3</isbn><title>Ajax Bible</title><authors><author>Steven Holzner</author></authors><publisher>Wiley</publisher></book><book><isbn>978-0-596-51774-8</isbn><title>JavaScript The Good Parts</title><authors><author>Douglas Crockford</author></authors><publisher>O'Reilly</publisher></book><book><isbn>978-0-596-80279-0</isbn><title>High Performance JavaScript</title><authors><author>Nicholas C. Zakas</author></authors><publisher>O'Reilly</publisher></book><book><isbn>978-0-975-8419-8-3</isbn><title>The CSS Anthology 101 Essential Tips, Tricks, and Hacks (2nd Edition)</title><authors><author>Rachel Andrew</author></authors><publisher>Sitepoint</publisher></book><book><isbn>978-0-596-80244-8</isbn><title>CSS The Missing Manual</title><authors><author>David Sawyer McFarland</author></authors><publisher>O'Reilly</publisher></book><book><isbn>978-0-321-71963-8</isbn><title>CSS 3</title><authors><author>Jason Cranford Teague</author></authors><publisher>Peachpit Press</publisher></book><book><isbn>978-0-672-32976-0</isbn><title>Sams Teach Yourself PHP, MySQL, and Apache</title><authors><author>Julie C. Meloni</author></authors><publisher>Sams</publisher></book><book><isbn>978-1-59059-689-0</isbn><title>Beginning CSS Web Development</title><authors><author>Simon Collison</author></authors><publisher>Apress</publisher></book><book><isbn>978-0-470-06916-5</isbn><title>JavaScript Bible</title><authors><author>Danny Goodman</author><author>Michael Morrison</author></authors><publisher>Wiley</publisher></book></books>

  • #4
    Senior Coder
    Join Date
    Jan 2011
    Location
    Missouri
    Posts
    4,686
    Thanks
    25
    Thanked 656 Times in 655 Posts
    Your xml was perfect! What I need is how does your client want to do this: The client would like it to read an XML file by using an input box to type in your query and display the results.
    And yes I can show you how to retrieve the information given an author's name.

  • #5
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,642
    Thanks
    0
    Thanked 649 Times in 639 Posts
    Quote Originally Posted by sunfighter View Post
    This will read an xml file for you and place it into a div. I know that's not what you want but it's a start. "xmlhttp.responseText" is the returned file and you can now do with it as you like.
    Why would responseText be referenced when the info being returned is XML - surely processing it from responseXML where you can then use DOM calls to access the individual elements within it would be the far easier option.


    for example you could obtain all the ISBN values using

    xmlhttp.responseXML.getElementsByTagName('isbn')
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #6
    New to the CF scene
    Join Date
    Oct 2012
    Posts
    7
    Thanks
    0
    Thanked 1 Time in 1 Post
    Yes, an input box is needed to search via the author, no mouse will be provided on the terminals in which this will be accessed so it needs to function with a keyboard only. So basically once a letter is typed in, the xml file is being searched, displaying a list of authors below the text box itself and then you can down arrow and select the one you wanted.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •