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
    Jun 2006
    Posts
    17
    Thanks
    0
    Thanked 0 Times in 0 Posts

    AJAX "POST" problems

    So here's what I'm trying to accomplish basically. I want to have an almost "live" chat, so I figured AJAX would be perfect for what I wanted.

    So far, I've managed to get AJAX to retrieve any updates in the chatbox. That was pretty simple. My real problem however, is trying to get AJAX to send data over POST. It just won't work for me... and the frustration is killing me.

    It just doesn't seem to even try the function I'm telling it to do. I press the button, and it attempts to load the page again... which I don't think it should?
    No data is sent. Huh?

    My page consists of 4 seperate pages. The index, getnew.php, which queries the database for the latest messages, addnew.php, which should be self-expanitory, and an HTML forms page.

    Here is the index page, which consists of all my Javascript code. (Sorry ahead of time if it's hard to read... I usually make my code all pretty after I'm done... :P)

    Code:
    var url = "getnew.php";
    
    var urlPost = "addnew.php";
    
    var params = "";
    
    http_request = getHTTP();
    
    getChatData();
    
    function getHTTP() {
    
    	if (window.XMLHttpRequest) { // Mozilla, Safari, ...
            http_request = new XMLHttpRequest();
            if (http_request.overrideMimeType) {
                http_request.overrideMimeType('text/xml');
            }
        } else if (window.ActiveXObject) { // IE
            try {
                http_request = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    http_request = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {}
            }
        }
    	
    	return http_request;
    }
    
    function getChatData() {
    
        http_request.onreadystatechange = chatData;
        http_request.open('GET', url, true);
        http_request.send(null);
    	
    	setTimeout('getChatData()', 1500);
    	
    }
    
    function sendChatData() {
    
    http.open("POST", urlPost, true);
    
    //Send the proper header information along with the request
    http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    //http_request.setRequestHeader("Content-length", params.length);
    //http_request.setRequestHeader("Connection", "close");
    
    http_request.onreadystatechange = function() {//Call a function when the state changes.
    
    	if (http_request.readyState == 4 && http.status == 200) {
    	
    		//chatText = encodeURIComponent(document.forms['chat_form'].elements['msg'].value);
    
    		//chatName = encodeURIComponent(document.forms['chat_form'].elements['name'].value);
    			
    		params = "n=" + chatName + "&text=" + chatText;
    		
    		alert(chatText + chatName);
    		
    	}
    	
    }
    
    http_request.send(params);
    
    alert(http_request.reponseText);
    
    /*
    
    	http_request.onreadystatechange = sendData;
    
    	param = "n=" + chatName + "&text=" + chatText;
    	http_request.open("POST", urlPost, true);
    	http_request.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    	http_request.send(param);
    	
    	*/
    	
    }
    
    function chatData() {
    
            if (http_request.readyState == 4) {
    		
                if (http_request.status == 200) {
    				
    				document.getElementById("chat_area").innerHTML = http_request.responseText;
    			   
    			  }
    			  
            } 
    		
    }
    My forms page
    Code:
    <form id="chat_form" name="chat_form" method="POST" action="">
    Name: <input type="text" name="name" maxlength="20" id="name" size="21">
    Message: <input type="text" name="msg" maxlength="100" id="msg" size="85">
    <input type="submit" value="SayIt" id="submit" onclick="sendChatData()">
    </form>
    And my "addnew.php" page

    PHP Code:
    <?

    include("connect.php");

    $name $_POST['n'];

    $msg $_POST['text'];

    if ( (!(isset(
    $name))) || (!(isset($msg))) ) {

        die(
    "unset variables");
        
    }

    mysql_query("INSERT INTO ajax_tbl (msg_author, msg_text) VALUES ('$name', '$msg')") or die(mysql_error());

    ?>
    My "getnew.php" isn't causing any troubles, so I won't post it unless needed.

    Any ideas? (Sorry if I missed something important, just let me know)

  • #2
    Senior Coder
    Join Date
    Sep 2005
    Posts
    1,791
    Thanks
    5
    Thanked 36 Times in 35 Posts
    you want your submit function to be attached to onsubmit, and for it to return false, so that the form isn't actually submitted (you could instead make it type 'button' rather than 'submit' and stick with 'onclick').

  • #3
    New Coder
    Join Date
    Jun 2006
    Posts
    17
    Thanks
    0
    Thanked 0 Times in 0 Posts
    I tried this:

    Form page:
    Code:
    <form id="chat_form" name="chat_form" method="POST" action="">
    Name: <input type="text" name="name" maxlength="20" id="name" size="21">
    Message: <input type="text" name="msg" maxlength="100" id="msg" size="85">
    <input type="button" value="SayIt" id="submit" onclick="sendChatData()">
    </form>
    Modified "sendChatData()":
    Code:
    function sendChatData() {
    
    http.open("POST", urlPost, true);
    
    //Send the proper header information along with the request
    http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    //http_request.setRequestHeader("Content-length", params.length);
    //http_request.setRequestHeader("Connection", "close");
    
    http_request.onreadystatechange = function() {//Call a function when the state changes.
    
    	if (http_request.readyState == 4 && http.status == 200) {
    	
    		//chatText = encodeURIComponent(document.forms['chat_form'].elements['msg'].value);
    
    		//chatName = encodeURIComponent(document.forms['chat_form'].elements['name'].value);
    			
    		params = "n=" + chatName + "&text=" + chatText;
    		
    		alert(chatText + chatName);
    		
    	}
    	
    }
    
    http_request.send(params);
    
    alert(http_request.reponseText);
    
    return false;
    
    }
    It still fails to send anything... grrr.

  • #4
    New Coder
    Join Date
    Dec 2006
    Posts
    38
    Thanks
    0
    Thanked 0 Times in 0 Posts
    youre defining the params variable inside the function that gets called when the request has gotten a response from the server which makes no sense, since that happens after you send obviously ;D

    Code:
    params = "n=" + chatName + "&text=" + chatText;
    http_request.send(params);
    like this.

    You use onreadystatechange to deal with the response from the server. Like in your example when its done (readyState == 4) and has gotten an okay response from the server (200 , url exists and can be accessed)
    http://demo.vegui.org - vegUI AJAX framework
    http://www.landsofkazram.com - browser based graphical MMORPG

  • #5
    New Coder
    Join Date
    Jun 2006
    Posts
    17
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Okay, so I tried that too... here is my new code for the function:

    Code:
    function sendChatData() {
    
    http.open("POST", urlPost, true);
    
    //Send the proper header information along with the request
    http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    //http_request.setRequestHeader("Content-length", params.length);
    //http_request.setRequestHeader("Connection", "close");
    
    http_request.onreadystatechange = function() {//Call a function when the state changes.
    
    	if (http_request.readyState == 4 && http.status == 200) {
    	
    		//chatText = encodeURIComponent(document.forms['chat_form'].elements['msg'].value);
    
    		//chatName = encodeURIComponent(document.forms['chat_form'].elements['name'].value);
    			
    		params = "n=" + chatName + "&text=" + chatText;
    		
    		alert(chatText + chatName);
    		
    		http_request.send(params);
    		
    		
    		
    	}
    	
    }
    
    return false;
    
    alert(http_request.reponseText);
    
    	
    }
    Still won't send anything...

    Oh, I forgot this as well.. here's my script running: Clicky
    Last edited by Drevin; 12-22-2006 at 09:22 PM. Reason: added live script link

  • #6
    Senior Coder
    Join Date
    Sep 2005
    Posts
    1,791
    Thanks
    5
    Thanked 36 Times in 35 Posts
    your calling
    'http.open'
    but your xhr object is http_request. The comparison on the returned data is using both:
    Code:
    if (http_request.readyState == 4 && http.status == 200) {
    you still have the .send() inside the callback, which makes little sense...

    have you considered using an existing AJAX library, such as Prototype's to save yourself time and effort?
    http://prototype.conio.net/ and http://www.sergiopereira.com/articles/prototype.js.html


    You might want to install the Firebug firefox extension (http://www.getfirebug.com) as it gives helpful javascript error messages

  • #7
    New Coder
    Join Date
    Jun 2006
    Posts
    17
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Okay... your suggestion worked... partially. I installed FireBug (This is a godsend), and it seems theres some errors definitely happening. It actually did POST successfully once, but otherwise it has an error. It will execute sometimes, but with no POSTing happening. Here is the usual culprit:

    Code:
    uncaught exception: [Exception... "Component returned failure code: 0x804b000f [nsIXMLHttpRequest.setRequestHeader]" nsresult: "0x804b000f (<unknown>)" location: "JS frame :: http://www.nintendoconnection.net/scripts/chat/ajax/ajax_dbox.php :: sendChatData :: line 47" data: no]
    
    [Exception... "Component returned failure code: 0x80040111 (NS_ERROR_NOT_AVAILABLE) [nsIXMLHttpRequest.status]" nsresult: "0x80040111 (NS_ERROR_NOT_AVAILABLE)" location: "JS frame :: http://www.nintendoconnection.net/scripts/chat/ajax/ajax_dbox.php :: chatData :: line 77" data: no]
    
    if (http_request.status == 200) {
    My new function:
    Code:
    function sendChatData() {
    
    http_request.open("POST", urlPost, true);
    
    //Send the proper header information along with the request
    http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    //http_request.setRequestHeader("Content-length", params.length);
    //http_request.setRequestHeader("Connection", "close");
    
    http_request.onreadystatechange = function() {//Call a function when the state changes.
    
    	if (http_request.readyState == 4 && http_request.status == 200) {
    	
    		chatText = encodeURIComponent(document.forms['chat_form'].elements['msg'].value);
    
    		chatName = encodeURIComponent(document.forms['chat_form'].elements['name'].value);
    			
    		params = "n=" + chatName + "&text=" + chatText;
    		
    		alert(chatText + chatName);
    		
    	}
    	
    }
    
    http_request.send(params);
    
    return false;
    	
    }
    I was thinking of making two http_requests, one for receiving, and one for sending. I got an error once where it appeared the two were conflicting. I'll try that.

    I noticed that sometimes it tends to lock up trying to get more data... after so many requests... it just seems to stop trying... weird.

  • #8
    New Coder
    Join Date
    Dec 2006
    Posts
    38
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Code:
    function sendChatData() {
    
    http_request.open("POST", urlPost, true);
    
    //Send the proper header information along with the request
    
    http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    http_request.onreadystatechange = function() {
    	if (http_request.readyState == 4 && http_request.status == 200) {
                alert(http_request.responseText);
    	}
    }
    	
    chatText = encodeURIComponent(document.forms['chat_form'].elements['msg'].value);
    chatName = encodeURIComponent(document.forms['chat_form'].elements['name'].value);	
    params = "n=" + chatName + "&text=" + chatText;
    
    http_request.send(params);
    
    return false;
    	
    }
    thats what i meant
    http://demo.vegui.org - vegUI AJAX framework
    http://www.landsofkazram.com - browser based graphical MMORPG

  • #9
    New Coder
    Join Date
    Jun 2006
    Posts
    17
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Ah, okay... thanks.

    Do you have any idea what might be causing those errors?

    Edit: Okay... its almost working. Once a post occurs, it POSTs just fine, but then my "GET" function ceases to work. I think its because of those errors.
    Last edited by Drevin; 12-23-2006 at 07:04 AM.

  • #10
    New Coder
    Join Date
    Jun 2006
    Posts
    17
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Bump... does anyone have any idea what is causing those errors? They are causing intermittent problems with the script.

  • #11
    New to the CF scene
    Join Date
    Oct 2012
    Location
    Jessore, KH 7400, Bangladesh
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Arrow The actual solution

    Quote Originally Posted by Drevin View Post
    Bump... does anyone have any idea what is causing those errors? They are causing intermittent problems with the script.
    I see the error details using FireBug,

    Don't ask what the problem just move your open request to top and this will be fixed.

    Example:

    http.open("POST","",true);
    http.setHeader();
    http.onreadystatechange=function(){
    //your code
    }
    http.send(params);

    Thanks,
    -Abbas Uddin

  • #12
    Regular Coder
    Join Date
    Apr 2012
    Location
    St. Louis, MO
    Posts
    985
    Thanks
    7
    Thanked 101 Times in 101 Posts
    The last post was almost 6 years ago.
    ^_^

    If anyone knows of a website that can offer ColdFusion help that isn't controlled by neurotic, pedantic jerks* (stackoverflow.com), please PM me with a link.
    *
    The neurotic, pedantic jerks are not the owners; just the people who are in control of the "popularity contest".


  •  

    Posting Permissions

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