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 12 of 12
  1. #1
    New Coder
    Join Date
    May 2009
    Location
    philippines
    Posts
    50
    Thanks
    6
    Thanked 1 Time in 1 Post

    AJAX query failed

    is it possible to configure the server so that any xmlhttprequest would be denied?

  • #2
    Regular Coder
    Join Date
    Feb 2009
    Location
    NJ, USA
    Posts
    476
    Thanks
    2
    Thanked 70 Times in 69 Posts
    Not that I know of. Why would you want to do that though?

  • #3
    New Coder
    Join Date
    May 2009
    Location
    philippines
    Posts
    50
    Thanks
    6
    Thanked 1 Time in 1 Post
    not that i wanted it though.. i was just wondering since i can't seem to make the ajax code that i've copied from a book to work on a borrowed server. i'm trying to figure out, who is at fault, or why i can't seem to make the code work..

  • #4
    Regular Coder
    Join Date
    Feb 2009
    Location
    NJ, USA
    Posts
    476
    Thanks
    2
    Thanked 70 Times in 69 Posts
    Hmm, well post your code so far and I'll take a look.

    Using a tool like Firebug can really help you write ajax code btw, as it will show you any error messages that come up when trying to run ajax requests.

    Also, one quick thing. Are you making an ajax request to the same server that the "host" page is on? I bring that up because a page cannot make an ajax request to an external server, and that's a common problem that people run into (if trying to retrieve weather information or whatnot).

    -Greg

  • #5
    New Coder
    Join Date
    May 2009
    Location
    philippines
    Posts
    50
    Thanks
    6
    Thanked 1 Time in 1 Post
    here are the codes, i've copied it from a book just to test it. i placed all of the files in the same folder in the server.

    the hmtl:
    Code:
    <html>
    <head>
    <title>Ajax Test</head>
    <script language="Javascript" type="text/javascript" src="ajax.js">
    </script>
    </head>
    <body>
    <h1>Ajax Quiz Example</h1>
    <form>
    <p><b>Questions:</b>
    <span id="question">...</span></p>
    <p><b>Answer:</b>
    <input type="text" name="answer" id="answer">
    <input type="button" value="Submit" id="submit">
    </p>
    <input type="button" value="Start the quiz" id="startq">
    </form>
    <script language="javascript" type="text/javascript" src="quiz.js">
    </script>
    </body>
    </html>
    the javascript files (there's two of them):
    (quiz.js)
    Code:
    var qn=0;
    function getQuestions() {
    	obj=document.getElementById("question");
    	obj.firstChild.nodeValue = "(please wait)";
    	ajaxCallback = nextQuestion;
    	ajaxRequest("questions.xml");
    }
    function nextQuestion() {
    	questions = ajaxreq.responseXML.getElementByTagName("q");
    	obj=document.getElementById("question");
    	if (qn < questions.length) {
    		q=questions[qn].firstChild.nodeValue;
    		obj.firstChild.nodeValue=q;
    	} else {
    		obj.firstChild.nodeValue="(no more questions)";
    	}
    }
    function checkAnswer() {
    	answers=ajaxreq.responseXML.getElementByTagName("a");
    	a = answer[qn].firstChild.nodeValue;
    	answerfield=document.getElementById("answer");
    	if (a == answerfield.value) {
    		alert("correct");
    	} else {
    		alert("incorrect, the answer is :" + a);
    	}
    	qn = qn + 1;
    	answerfield.value="";
    	nextQuestion();
    }
    obj=document.getElementById("startq");
    obj.onclick=getQuestions;
    ans=document.getElementById("submit");
    ans.onclick=checkAnswer;
    (ajax.js)
    Code:
    /* AJAX Library */
    //
    // global variables to keep track of the request and the function to call when done
    //
    
    var ajaxreq = false, ajaxCallback;
    
    // ajaxRequest: sets up a request
    
    function ajaxRequest(filename) {
    	try {
    		// firefox IE7 others
    		ajaxreq = new XMLHttpRequest();
    	} catch (error) {
    		try {
    			// IE5 IE6
    			ajaxreq = new ActiveXObject("Microsoft.XMLHTTP");
    		} catch (error) {
    			return false;
    		}
    	}
    	ajaxreq.open("GET", filename);
    	ajaxreq.onreadystatechange = ajaxResponse;
    	ajaxreq.send(null);
    }
    
    // ajaxResponse: waits for response and calls a function
    
    function ajaxResponse() {
    	if (ajaxreq.readystate != 4) {
    		return;
    	}
    	if (ajaxreq.status == 200) {
    		// if the request succeeded..
    		if (ajaxCallback) {
    			ajaxCallback();
    		}
    	} else {
    		alert("Request failed:  " + ajaxreq.statusText);
    	}
    	return true;
    }
    and finally, the xml file:
    (questions.xml)
    Code:
    <?xml version="1.0" ?>
    <questions>
    	<q>What DOM object contains URL information for the window?</q>
    	<a>location</a>
    	<q>Which method of the document object finds the object for an element?</q>
    	<a>getElementById</a>
    	<q>If you declare a variable outside a function, is it global or local?</q>
    	<a>global</a>
    </questions>

    i'll also try that firebug you've mentioned.

    thank you..

  • #6
    Regular Coder
    Join Date
    Feb 2009
    Location
    NJ, USA
    Posts
    476
    Thanks
    2
    Thanked 70 Times in 69 Posts
    Man, gotta tell ya, this code is pretty terrible... What book are you getting this from? I guess for this simple app it's alright, but that ajax.js file, with its use of global variables, would not be good as an ajax library file to rely on (it will break your code when multiple requests are made at once).

    But ok, believe it or not, your AJAX request is actually running fine. The browser is correctly retrieving the data in the XML file from the server. If you're using Firefox and have installed Firebug, you will see a GET request being made in the Firebug console, having the "200 OK" code returned. If you expand that, you will see your XML data as the "response" from the request.

    The actual problem lies in the fact that the ajaxCallback is never called. So basically, your code that is supposed to handle the XML document being loaded, is never run. The reason for this is in the ajaxResponse() function, you have ajaxreq.readystate in all lowercase letters. It needs to be ajaxreq.readyState (capital S, as JavaScript is case sensitive). So because ajaxreq.readystate is never equal to 4 (it is undefined), the ajaxResponse() function never gets past that first if statement (therefore never calling your ajaxCallback() function).

    So after changing that, the next thing I ran across is you trying to use the getElementByTagName() method on the XML. The method is actually called getElementsByTagName() (to account for the possibility of more than one element of the same name). Then with one other quick tweak (changing answer[qn] to answers[qn]), the code works fine

    Here are the corrections that I made to get it to work. Highlighted the changes in red.

    ajax.js
    Code:
    /* AJAX Library */
    //
    // global variables to keep track of the request and the function to call when done
    //
    
    var ajaxreq = false, ajaxCallback;
    
    // ajaxRequest: sets up a request
    function ajaxRequest( filename ) {
        try {
            // firefox IE7 others
            ajaxreq = new XMLHttpRequest();
        } catch( error ) {
            try {
                // IE5 IE6
                ajaxreq = new ActiveXObject( "Microsoft.XMLHTTP" );
            } catch( error ) {
                return false;
            }
        }
        ajaxreq.open( "GET", filename );
        ajaxreq.onreadystatechange = ajaxResponse;
        ajaxreq.send( null );
    }
    
    // ajaxResponse: waits for response and calls a function
    function ajaxResponse() {
        if( ajaxreq.readyState != 4 ) {
            return;
        }
        if( ajaxreq.status == 200 ) {
            // if the request succeeded..
            if( ajaxCallback ) {
                ajaxCallback();
            }
        } else {
            alert( "Request failed:  " + ajaxreq.statusText );
        }
        return true;
    }
    quiz.js
    Code:
    var qn=0;
    
    function getQuestions() {
        obj = document.getElementById( "question" );
        obj.firstChild.nodeValue = "(please wait)";
        ajaxCallback = nextQuestion;
        ajaxRequest( "questions.xml" );
    }
    
    function nextQuestion() {
        questions = ajaxreq.responseXML.getElementsByTagName( "q" );
        obj = document.getElementById( "question" );
        
        if( qn < questions.length ) {
            q = questions[ qn ].firstChild.nodeValue;
            obj.firstChild.nodeValue = q;
        } else {
            obj.firstChild.nodeValue = "(no more questions)";
        }
    }
    
    function checkAnswer() {
        answers = ajaxreq.responseXML.getElementsByTagName( "a" );
        a = answers[ qn ].firstChild.nodeValue;
        answerfield = document.getElementById( "answer" );
        
        if( a == answerfield.value ) {
            alert( "correct" );
        } else {
            alert( "incorrect, the answer is :" + a );
        }
        qn = qn + 1;
        answerfield.value = "";
        nextQuestion();
    }
    
    obj = document.getElementById( "startq" );
    obj.onclick = getQuestions;
    
    ans = document.getElementById( "submit" );
    ans.onclick = checkAnswer;
    Try that and let me know how it goes.

    -Greg

  • Users who have thanked Gjslick for this post:

    sim_pack (05-19-2010)

  • #7
    New Coder
    Join Date
    May 2009
    Location
    philippines
    Posts
    50
    Thanks
    6
    Thanked 1 Time in 1 Post
    wow, so much trouble just because of one letter.. thank you so much for your help, am going to get a go at it again later..

    btw, the codes are from sams teach yourself javascript in 24hrs. that's probably the reason why the codes can be so terrible, the book teaches javascript in so short a time that it trade off better codes.

    thank you again mate..

  • #8
    New Coder
    Join Date
    May 2009
    Location
    philippines
    Posts
    50
    Thanks
    6
    Thanked 1 Time in 1 Post
    hello greg, just got back from testing the codes again and as you said it would, it really is working.. thanks again..

    am going back now to tweaking the codes and experimenting.. cheers!

  • #9
    Regular Coder
    Join Date
    Feb 2009
    Location
    NJ, USA
    Posts
    476
    Thanks
    2
    Thanked 70 Times in 69 Posts
    No problem dude Glad you got it all working! And feel free to post again if you need anything else

    -Greg

  • #10
    New Coder
    Join Date
    May 2009
    Location
    philippines
    Posts
    50
    Thanks
    6
    Thanked 1 Time in 1 Post
    Quote Originally Posted by Gjslick View Post
    Man, gotta tell ya, this code is pretty terrible... What book are you getting this from? I guess for this simple app it's alright, but that ajax.js file, with its use of global variables, would not be good as an ajax library file to rely on (it will break your code when multiple requests are made at once).
    this thing (above quote) hit me sloooowly. can you point me to a better way of making the ajax library so it won't break if multiple requests are made?

    thanks again..

  • #11
    Regular Coder
    Join Date
    Feb 2009
    Location
    NJ, USA
    Posts
    476
    Thanks
    2
    Thanked 70 Times in 69 Posts
    Here's a (relatively) simple AJAX class that I got a while back from the book "AJAX Web Applications" (a sitepoint book), and used for a number of years. With this, a new instance of the Ajax class can be created for each new request that needs to be made, without worrying about interfering or overwriting a previous request (which would happen with your current code).

    Ajax.js
    Code:
    function Ajax() {
        this.request = null
        this.url = null;
        this.method = 'GET';
        this.async = true;
        this.status = null;
        this.statusText = '';
        this.postData = null;
        this.readyState = null;
        this.responseText = null;
        this.responseXML = null;
        this.handleNoAjax = null;
        this.handleResponse = null;
        this.responseFormat = 'text';  // 'text', 'xml', or 'object'
    
    
        // Set No Ajax Handler
        this.setNoAjaxHandler = function( funcRef ) {
            this.handleNoAjax = funcRef;
        }
        
        // Set Error Handler
        this.setErrorHandler = function( funcRef ) {
            this.handleError = funcRef;
        }
    
        // Init Function
        this.init = function() {
            if( !this.request ) {
                try {
                    this.request = new XMLHttpRequest();          // Try to create object for Firefox, Safari, IE7, etc.
                } catch( e ) {
                    try {
                        this.request = new ActiveXObject( 'MSXML2.XMLHTTP' );            // Try to create object for later versions of IE
                    } catch( e ) {
                        try {
                            this.request = new ActiveXObject( 'Microsoft.XMLHTTP' );     // Try to create object for early versions of IE
                        } catch( e ) {
                            return false;      // Could not create an XMLHttpRequest object
                        }
                    }
                }
            }
            return this.request;
        }
        
        
        // Do Request
        this.doRequest = function() {
            if( !this.init() ) {
                if( this.handleNoAjax ) this.handleNoAjax();
                return false;
            }
                        
            this.request.open( this.method, this.url, this.async );
            
            if( this.method == "POST" ) 
                this.request.setRequestHeader( 'Content-Type', 'application/x-www-form-urlencoded' );
                
                
            // On Ready State Change Event Handler Function
            var self = this;
            this.request.onreadystatechange = function() {
                var response;
                if( self.request.readyState == 4 ) {
                    switch( self.responseFormat ) {
                        case 'text' :
                            response = self.request.responseText;
                            break;
                        case 'xml' :
                            response = self.request.responseXML;
                            break;
                        case 'object' :
                            response = self.request;
                            break;
                    }
                
                    if( self.request.status >= 200 && self.request.status <= 299 ) {
                        self.handleResponse( response );
                    } else {
                        self.handleError( response );
                    }
                }
            }
            
            // Send Request
            this.request.send( this.postData );
            return true;
        }
        
        
        // Do Get
        this.doGet = function( url, responseHandler, format ) {
            this.abort();    // Abort any previous request that has not finished
            
            this.url = url;
            this.handleResponse = responseHandler;
            this.responseFormat = format || 'text';
            return this.doRequest();
        }
        
        // Do Post
        this.doPost = function( url, postData, responseHandler, format ) {
            this.abort();    // Abort any previous request that has not finished
            
            this.url = url;
            this.handleResponse = responseHandler;
            this.responseFormat = format || 'text';
            this.method = 'POST';
            this.postData = postData;
            return this.doRequest();
        }
        
        
        // Abort Request
        this.abort = function() {
            if( this.request ) {
                this.request.onreadystatechange = function() { };
                this.request.abort();
                this.request = null;
            }
        }
        
        
        // Default Error Handler
        this.handleError = function( responseText ) {
            alert( 'An unexpected error has occurred.\n'
                            +    'Status Code: ' + this.request.status + '\n'
                            + 'Status Description: ' + this.request.statusText
                            + 'Response Text: ' + this.request.responseText );
        }
    }
    And here are a few a test files to help show you how to use it a bit.
    index.html
    Code:
    <html>
    
    <head>
        <script src="/jslib/Ajax.js"></script>
        <script>
            window.onload = function() {
                
                /* Example of a GET request */
                
                function handleGet( response ) {
                    document.getElementById( 'output' ).innerHTML += response;
                }
                var ajax = new Ajax();
                ajax.doGet( 'test.php', handleGet, 'text' );  // last arg can be 'text', 'xml', or 'object'
                
                
                
                /* Example of a POST request */
                
                function handlePost( response ) {
                    document.getElementById( 'output' ).innerHTML += response;
                }
                var ajax2 = new Ajax();    // a new AJAX object who's request can run at the same time that the first ajax request is running
                var params = "p1=val1&p2=val2";
                ajax2.doPost( 'test.php', params, handlePost, 'text' );  // last arg can be 'text', 'xml', or 'object'
            }
        </script>
    </head>
    
    
    <body>
        <div id="output"></div>
    </body>
    
    </html>
    test.php
    PHP Code:
    <?php

    if( count$_POST ) == )
        echo 
    "[GET request response]<br>";
    else
        echo 
    "[POST request response: {$_POST['p1']} {$_POST['p2']} ]<br>";

    ?>
    With using that Ajax class, you can also perform multiple requests with the same instantiated ajax object, but a new request that is made on that object will have the effect of aborting any previous request that is still running from that object (which is actually a desirable feature). So just remember to use two separate Ajax objects when you have two different things that need to be requested at the same time.

    That Ajax class is a good lightweight utility for making ajax requests, but if you don't mind including a larger library onto your pages, then I'd recommend using the ajax functionality provided with one of the popular JavaScript frameworks, such as jQuery, MooTools, YUI, or ExtJs. jQuery is by far the most popular, and running ajax requests through it are very simple after you have included the jQuery source file onto your page. Check this link for details: http://api.jquery.com/jQuery.ajax/ The examples on that page should get you started if you want to go that route.

    -Greg

  • #12
    New Coder
    Join Date
    May 2009
    Location
    philippines
    Posts
    50
    Thanks
    6
    Thanked 1 Time in 1 Post
    that's great!! i'll dive into it. thanks again for the valuable help..
    cheers mate..


  •  

    Posting Permissions

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