Ajax Script Returns Value, But Doesn't Display It

Discussion in 'JavaScript' started by HaunahLee, Apr 10, 2007.

  1. #1
    I have an Ajax/JS enabled page that sends a request and gets a response from the server, but I can't get it to display the result on the page.

    I'm using FireBug (Firefox JS debugging extension) and the response from the server side script shows up in the debugger. But When I try to display it on the page with "alert(ajax.responseText);" I get an empty alert box.

    This is the script on the main page:

    
    <SCRIPT src='../../include/ajax/ajax_basic.js'></SCRIPT>
    <SCRIPT type="text/javascript">
    
    var ajax;
    
    function display_body (key)
        {
        
        ajax = create_ajax(); // Create an HTTP request object nammed 'ajax'
        
        if (ajax==null)// The creation failed
            {
            alert ("Browser does not support HTTP Request");
            return;
            }
        
        var url="../../include/ajax/FAQ_answer.php";
        url=url+"?string="+key;
        ajax.onreadystatechange=update_page('faq_field', ajax);
        alert(ajax.responseText);
        ajax.open("GET",url,true);
        ajax.send(null);
        }
    
    </SCRIPT>
    
    PHP:
    And this is the script in the included file:

    
    function update_page(id, ajax)
        {
        id = "'" + id + "'";
        alert(ajax.responseText);
        if (ajax.readyState==4 || ajax.readyState=="complete")
            {
            if (ajax.status == 200)
                {
                alert("we made contact");
                document.getElementById(id).innerHTML=ajax.responseText;
                }
                else
                {
                alert("The Ready State is Four, but the response is NOT 'OK'");
                }
            }
        }    
    
    function create_ajax()
        {
    
        ajax=null;
        try
            {
            // Firefox, Opera 8.0+, Safari
            ajax=new XMLHttpRequest();
            }
            catch (e)
            {
            //Internet Explorer
            try
                {
                ajax=new ActiveXObject("Msxml2.XMLHTTP");
                }
                catch (e)
                {
                ajax=new ActiveXObject("Microsoft.XMLHTTP");
                }
            }
        return ajax;
        }
    
    PHP:
    If someone could tell me what I'm doing wrong, it would be greatly appreciated.

    Thanks!
     
    HaunahLee, Apr 10, 2007 IP
  2. briansol

    briansol Well-Known Member

    Messages:
    221
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    110
    #2
    briansol, Apr 11, 2007 IP
  3. Adi

    Adi Peon

    Messages:
    23
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    I don't have exact answer to what exactly you are "doing wrong" (I don't debug at home :) ) but:
    1. As Briansol wrote, you use a global variable and pass it to each function. WHY ? Your infrastructure will fail when there will be more then one Ajax call on the page !

    2. The create_ajax() is an example of how not to program :( - exceptions are here to be avoided, there are better ways to identify the type of browser + you forgot to check for Msxml3.XMLHTTP, Msxml4.XMLHTTP and Msxml6.XMLHTTP

    To solve the problem
    Start with simple code without functions, without aync call (send false to the 3rd open parameter) and make that code work. Then you will be able to gradually add abilities to get solid infrastructure.

    Good luck.
     
    Adi, Apr 11, 2007 IP
  4. HaunahLee

    HaunahLee Peon

    Messages:
    6
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Since the alert box was returning null, i passed the value to the function out of desperation.

    I got that from a tutorial somewhere. I'll try simplyfying and build from the ground up as you sugguest. Thanks guys for your sugguestions! :)
     
    HaunahLee, Apr 11, 2007 IP
  5. HaunahLee

    HaunahLee Peon

    Messages:
    6
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Got it working using a basic testing file. The code is below. I do get an error in FireBug though. It seems to occur only when Async is false, and when I type multiple letters before an entire request completes itself.


    The error is:

    [Exception... "'Permission denied to set property XULElement.selectedIndex' when calling method: [nsIAutoCompletePopup::selectedIndex]"  nsresult: "0x8057001e (NS_ERROR_XPC_JS_THREW_STRING)"  location: "JS frame :: javascript: eval(__firebugTemp__); :: anonymous :: line 1"  data: no]
    javascript: eval(__firebugTemp__);
    Line 1
    Code (markup):
    Google says it's a Firefox bug, but I turned auto-compete off, and it still occurs.


    Code is:

    <SCRIPT type="text/javascript">
    var ajax;
    
    function display_body(key)
    	{
    	ajax=null; // Create an HTTP request object nammed 'ajax'
    		try
    			{
    			// Firefox, Opera 8.0+, Safari
    			ajax=new XMLHttpRequest();
    			}
    			catch (e)
    			{
    			//Internet Explorer
    			try
    				{
    				ajax=new ActiveXObject("Msxml2.XMLHTTP");
    				}
    				catch (e)
    				{
    				ajax=new ActiveXObject("Microsoft.XMLHTTP");
    				}
    			}
    			
    		if (ajax==null)// The creation failed
    			{
    			alert ("Browser does not support HTTP Request");
    			return;
    			}
    		
    		var url="ajax/FAQ_answer.php";
    		url=url+"?string="+key;
    		ajax.open("GET",url,true);
    		ajax.onreadystatechange = function ()
    			{
    			if (ajax.readyState==4 || ajax.readyState=="complete")
    				{
    				if (ajax.status == 200)
    					{
    					document.getElementById('faq_field').innerHTML=ajax.responseText;
    					}
    					else
    					{
    					alert("The Ready State is Four, but the response is NOT 'OK'");
    					}
    				}
    			};
    		ajax.send(null);
    	}		
    				
    </SCRIPT>
    
    <form>
    <input type='text' autocomplete='false' onkeyup='display_body(this.value);' />
    </form>
    <div id='faq_field'>This is some stupid text. </div>
    PHP:
    I will work on implementing this working code back into the page it's supposed to be on. Thanks again! ~Haunah
     
    HaunahLee, Apr 11, 2007 IP
  6. HaunahLee

    HaunahLee Peon

    Messages:
    6
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #6
    Ok, here's what found out:

    You can't call a function from onreadystatechange directly. You have to set it = to a function and use the function to call a function. How stupid is that? I.e.

    This works:

    ajax.onreadystatechange= function () {update_page("faq_field");};
    PHP:
    and this doesn't

    ajax.onreadystatechange= update_page("faq_field");
    PHP:
     
    HaunahLee, Apr 12, 2007 IP
  7. Adi

    Adi Peon

    Messages:
    23
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #7
    The onreadystatechange property should be set to a function "pointer" ... you have created anonymous function in your fixed code. You could have also use "ajax.onreadystatechange= update_page; " where update_page is the function which will be called when the state changes.

    For more info:
    http://www.w3schools.com/xml/xml_http.asp
     
    Adi, Apr 12, 2007 IP
  8. HaunahLee

    HaunahLee Peon

    Messages:
    6
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #8
    But when you pass arguments within the function, that's what causes it to break. I would have to do:

    
    var id="faq_field";
    ajax.onreadystatechange= update_page;
    
    PHP:
    Would it be legal to use:

    ajax.onreadystatechange= function call_function_with_parameters() {update_page("faq_field");};
    PHP:
    That way the function is no longer anonomoys?
     
    HaunahLee, Apr 12, 2007 IP