Forum Moderators: open

Message Too Old, No Replies

xmlhttp.open failed

         

snehula

1:22 pm on Jun 2, 2011 (gmt 0)

10+ Year Member



Hi there lads!

I'm just taking my first steps trying to use ajax, so be patient with me :-))
I get the above error trying to execute the following:
xmlHttp.open("POST","whatever.php", true)


well i get the error because i defined it:
if(!xmlHttp.open("POST","whatever.php", true)) {alert("xmlHttp.open failed");}


the whole function looks like:

function ajax() {

if(xmlHttp.readyState == 4 && xmlHttp.status == 200)
{
xmlHttp.open("POST","whatever.php", true);
if(!xmlHttp.open("POST","whatever.php", true)) {alert("xmlHttp.open failed");}
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send();
}
else setTimeout('ajax()',1000);

}


i verified that the xmlhttp object was created, the url is valid (it is in the same folder as the current page), where am i making a mistake?

snehula

2:17 pm on Jun 2, 2011 (gmt 0)

10+ Year Member



so, i removed the quotes around the url, if that should be the mistake, but either way, nothing's happening.

i got rid of the readystate and status check (if blaablaa)and again, nothing.. not even the alert.. nothing after the xmlHttp.open call... NOTHING! what is going oooooon?

JAB Creations

3:54 pm on Jun 2, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You are testing locally first correct? First off are you checking the JavaScript error consoles? Opera is the best for that and while Firefox is generally good it won't display all errors. Secondly you should be using access logs preferably with Tail for win32 to see where the request lands on your local server as well as Fiddler2. Presuming you know the difference between an HTTP 200 and an HTTP 404 those options alone will help you greatly.

- John

snehula

10:05 am on Jun 7, 2011 (gmt 0)

10+ Year Member



well the error console in opera says

Event thread: click
Uncaught exception: ReferenceError: Undefined variable: whatever
Error thrown at line 55, column 2 in ajax() in [localhost...]
if(!xmlHttp.open("POST",whatever.php, true))
called from line 1, column 0 in <anonymous function>(event):
ajax()


so, me doing this the first time, dunno what's going on since the name of the php script i'm trying to connect to in the open call is correct, tried with or without quotes, same thing happens..

snehula

10:42 am on Jun 7, 2011 (gmt 0)

10+ Year Member



another thing is, i have done the same thing before without using ajax, submitting a form using the $_POST array with php, now since i'm trying this with ajax i can forget about that right?
I need to check for empty textfields and build a parameter string, all with javascript and then send that as the send method parameter in the form
"value1="+var1+"&value2="+var2 etc.. is that right?

"there are no stupid questions only stupid people" :-)))

snehula

11:26 am on Jun 7, 2011 (gmt 0)

10+ Year Member



part 2:

..and then those params sent with ajax are stored in the $_POST array that i can use in my php script, as $_POST['value1']= var1 etc? hehhe i seem to be pretty confused :-)

JAB Creations

5:04 pm on Jun 7, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Undefined variable: whatever


'whatever.php' is not a valid internet address. http://www.example.com/whatever.php is.

- John

astupidname

8:51 am on Jun 8, 2011 (gmt 0)

10+ Year Member



another thing is, i have done the same thing before without using ajax, submitting a form using the $_POST array with php, now since i'm trying this with ajax i can forget about that right?


I'd say that's wrong, keep the non-javascript functionality available for people with javascript disabled.

..and then those params sent with ajax are stored in the $_POST array that i can use in my php script, as $_POST['value1']= var1 etc?


True.

'whatever.php' is not a valid internet address


It is, however, a valid relative url for an ajax request, given that you treat it as a string and wrap it in quote marks properly. Else if you do not wrap it in quotes then
whatever

would be seen as an attempt to access a variable named "whatever" and looking for a "php" property within it if doing:
whatever.php
. However, in your code you posted:

function ajax() {

if(xmlHttp.readyState == 4 && xmlHttp.status == 200)
{
xmlHttp.open("POST","whatever.php", true);
if(!xmlHttp.open("POST","whatever.php", true)) {alert("xmlHttp.open failed");}
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send();
}
else setTimeout('ajax()',1000);

}


I do not see that as being an issue in the above, as you have indeed properly wrapped the url "whatever.php" in quotes like <--- that. I do however see several errors and there are things you are not showing us here which also may be of help, but nevertheless:
In the above you access the ajax object referring to it initially as "xmlHttp", but then later access it as "http" ? What gives with that? Should http not be xmlHttp instead? Also, (for the duration I will refer to a created ajax object as "xmlHttp") xmlHttp's "open" method does not return a value and therefore always returns undefined. So, do not check for a return value from open().

I think your ajax function may work properly (not knowing exactly how you are going about the creation of the xmlHttp object) like this:

function ajax() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
xmlHttp.open("POST","whatever.php", true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(''); //note we are still missing any parameters to send here... will address later below in example
} else {
setTimeout(ajax, 1000); //never pass strings to setTimeout (I know the tutorials show it often,
//but that's wrong, use functions or anonymous functions only)
}
}



Now, another thing, it looks to me, because of the setTimeout, that you are wanting to continuously poll the server via ajax every second (one second after each completed ajax request, that is)? Is that right? I confess, I may be a bit confused as your "ajax" function actually looks to be an onreadystatechange handler which passes off a new ajax request using "handleServerResponse" as the name of another function to handle the results of the next request? Don't know what's with the daisy chaining going on there. Don't see how that would be necessary if all you are doing is submitting a form via ajax.
But I also don't see anywhere's where you are actually doing this:

I need to check for empty textfields and build a parameter string, all with javascript and then send that as the send method parameter in the form
"value1="+var1+"&value2="+var2 etc.. is that right?

astupidname

8:52 am on Jun 8, 2011 (gmt 0)

10+ Year Member



Here is a simple ajax form example, using POST, to get you going hopefully you can build on it if need be:

The html page:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
<title>Simple ajax form</title>
<script type="text/javascript">

function getXhr() {
var xhr = null;
try{//Mozilla, Safari, IE 7+...
xhr = new XMLHttpRequest();
if (xhr.overrideMimeType) {
xhr.overrideMimeType('text/xml');
}
} catch(e) {// IE 6, use only Msxml2.XMLHTTP.(6 or 3).0,
//see: http://blogs.msdn.com/xmlteam/archive/2006/10/23/using-the-right-version-of-msxml-in-internet-explorer.aspx
try{
xhr = new ActiveXObject("Msxml2.XMLHTTP.6.0");
}catch(e){
try{
xhr = new ActiveXObject("Msxml2.XMLHTTP.3.0");
}catch(e){}
}
}
return xhr;
}

function ajax(form) {
var xhr = getXhr(),
url = 'POST_Echoer.php',
value1 = form.field1.value,
value2 = form.field2.value,
requestID = new Date().getTime(),
//url query string variable values which may contain special characters,
//such as spaces, ?, etc. should be escaped, use encodeURIComponent:
query = 'value1='+ encodeURIComponent(value1) +'&value2='+ encodeURIComponent(value2);
query += '&requestID='+ requestID;
xhr.onreadystatechange = function () {
if (xhr.status == 200 && xhr.readyState == 4) {
alert(xhr.responseText.replace(/<br>/g, '\n'));
}
};
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.setRequestHeader('Content-Length', query.length);
xhr.setRequestHeader('Cache-Control', 'no-cache');
xhr.setRequestHeader("Connection", "close");
xhr.send(query);
}

</script>
</head>
<body>
<div>
<form name="someForm" action="POST_Echoer.php" method="post">
<p><input type="text" name="field1" value="Enter a value, or not..." size="25"><br>
<input type="text" name="field2" value="Enter another value, or not..." size="25"><br>
<input type="submit" name="submit" value="Submit" onclick="ajax(this.form); return false;">
</p></form>
</div>
</body>
</html>


The "POST_Echoer.php" file for test purposes:
<?php
//>POST_Echoer.php

$s = (count($_POST)) ? 'POST fields received:<br><br>' : 'No POST fields received!';
foreach ($_POST as $key => $value) {
$s .= $key.' => '.$value.'<br>';
}
echo $s;

?>

If anybody's wondering, how to post formatted code on webmasterworld [webmasterworld.com]
Do not copy formatted code on webmasterworld from IE, use other browser such as Firefox.

[edited by: astupidname at 9:19 am (utc) on Jun 8, 2011]

astupidname

9:07 am on Jun 8, 2011 (gmt 0)

10+ Year Member



note I forgot to put in a check for the validity of the xhr variable after the definition of the query variable in the ajax function in my example, should be:
    if (xhr === null) {
return null;
}
xhr.onreadystatechange = etcetera etcetera...

It will practically never be null, but bad practice not to check it..

"There are no people who don't ask stupid questions" :)

snehula

12:19 am on Jun 9, 2011 (gmt 0)

10+ Year Member



hey thanks a million :-) i actually removed the settimeout a while ago, and then i changed the code according to your much appreciated advice :-) now the thing is, the php script is returning the info, which i was lucky enough to notice once only for about half a second before it disappeared. so, the ajax code goes like this:

function ajax()
{
var xmlHttp = createXmlHttpRequestObject(); //create request object
var params = buildparams(); //query string
var url = 'whatever.php';
xmlHttp.open("POST",url, true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.setRequestHeader('Cache-Control', 'no-cache');
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4 && xmlHttp.status == 200)
{
var textResponse = xmlHttp.responseText;
document.getElementById('servcont').innerHTML = textResponse;
}
}//end function (onreadystatechange)
xmlHttp.send(params);
}


the error console stays quiet, everything seems to be ok.
why does the textresponse disappear straight away after being loaded, if the ajax function is only called on a button click, there is no timeout set or anything like that? what in the name of the lord can i not see here?

astupidname

9:01 am on Jun 9, 2011 (gmt 0)

10+ Year Member



i was lucky enough to notice once only for about half a second before it disappeared
.....
.....
why does the textresponse disappear straight away after being loaded

Hmmm... don't know exactly why that would be, but I'm almost certain it's something other than your ajax function, as that looks good.
Can you give an example of what should be returned from the server? Are there any other functions working with the document.getElementById('servcont') DOM object? Which may be affecting it's innerHTML property as well?
Can you give example of the html you are using for the button, or how exactly you are implementing the click?

There are times when using innerHTML is not best, and may run in to clashes and various problems due to faulty code design.
But there are equally as many times that it is absolutely fine to use.
Key is to know what elements of the code will be dealing with that elements innerHTML and whether or not any other code will be altering it or relying on it's inner elements to maintain state in the DOM as far as the elements DOM properties and values are concerned.
I presume my example worked flawlessly for you, so just need to figure out what else is all different, and the error is most likely somewhere in between! You are able to do an alert of textResponse o.k. right?

snehula

12:27 pm on Jun 9, 2011 (gmt 0)

10+ Year Member



astupidname thanks for your help i really appreciate it! well i didn't have the return false statement after the call to ajax function in the button onclick event and that seems to have done the trick.. finally after a looong birth the baby is born :-)) i wud never have succeeded without your help! graaacias :-)