Go Back   CodingForums.com > :: Client side development > JavaScript programming

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 12-22-2006, 08:08 AM   PM User | #1
Drevin
New Coder

 
Join Date: Jun 2006
Posts: 17
Thanks: 0
Thanked 0 Times in 0 Posts
Drevin is an unknown quantity at this point
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)
Drevin is offline   Reply With Quote
Old 12-22-2006, 08:16 AM   PM User | #2
GJay
Senior Coder

 
Join Date: Sep 2005
Posts: 1,791
Thanks: 5
Thanked 36 Times in 35 Posts
GJay is on a distinguished road
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').
GJay is offline   Reply With Quote
Old 12-22-2006, 08:27 AM   PM User | #3
Drevin
New Coder

 
Join Date: Jun 2006
Posts: 17
Thanks: 0
Thanked 0 Times in 0 Posts
Drevin is an unknown quantity at this point
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.
Drevin is offline   Reply With Quote
Old 12-22-2006, 09:51 AM   PM User | #4
vegu
New Coder

 
Join Date: Dec 2006
Posts: 38
Thanks: 0
Thanked 0 Times in 0 Posts
vegu is on a distinguished road
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
vegu is offline   Reply With Quote
Old 12-22-2006, 09:21 PM   PM User | #5
Drevin
New Coder

 
Join Date: Jun 2006
Posts: 17
Thanks: 0
Thanked 0 Times in 0 Posts
Drevin is an unknown quantity at this point
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
Drevin is offline   Reply With Quote
Old 12-22-2006, 11:33 PM   PM User | #6
GJay
Senior Coder

 
Join Date: Sep 2005
Posts: 1,791
Thanks: 5
Thanked 36 Times in 35 Posts
GJay is on a distinguished road
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
GJay is offline   Reply With Quote
Old 12-23-2006, 01:11 AM   PM User | #7
Drevin
New Coder

 
Join Date: Jun 2006
Posts: 17
Thanks: 0
Thanked 0 Times in 0 Posts
Drevin is an unknown quantity at this point
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.
Drevin is offline   Reply With Quote
Old 12-23-2006, 04:58 AM   PM User | #8
vegu
New Coder

 
Join Date: Dec 2006
Posts: 38
Thanks: 0
Thanked 0 Times in 0 Posts
vegu is on a distinguished road
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
vegu is offline   Reply With Quote
Old 12-23-2006, 05:23 AM   PM User | #9
Drevin
New Coder

 
Join Date: Jun 2006
Posts: 17
Thanks: 0
Thanked 0 Times in 0 Posts
Drevin is an unknown quantity at this point
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..
Drevin is offline   Reply With Quote
Old 12-24-2006, 03:08 AM   PM User | #10
Drevin
New Coder

 
Join Date: Jun 2006
Posts: 17
Thanks: 0
Thanked 0 Times in 0 Posts
Drevin is an unknown quantity at this point
Bump... does anyone have any idea what is causing those errors? They are causing intermittent problems with the script.
Drevin is offline   Reply With Quote
Old 10-23-2012, 07:25 PM   PM User | #11
abbasuddin
New to the CF scene

 
Join Date: Oct 2012
Location: Jessore, KH 7400, Bangladesh
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
abbasuddin is an unknown quantity at this point
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
abbasuddin is offline   Reply With Quote
Old 10-23-2012, 07:39 PM   PM User | #12
WolfShade
Regular Coder

 
Join Date: Apr 2012
Location: St. Louis, MO, USA
Posts: 941
Thanks: 7
Thanked 95 Times in 95 Posts
WolfShade is an unknown quantity at this point
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".
WolfShade is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 02:10 AM.


Advertisement
Log in to turn off these ads.