Hi all,

I am using AJAX to submit a data from a web page, it is properly working on the local host (when test with the local machine it is ok). When access from another machine the pages are properly lord. But when send data it gives an http request error.

The following is the error message.

pls anyone can help me to find the reason for this...

ERROR
The requested URL could not be retrieved

While trying to process the request:

POST /OmniPreferedRoaming/Omni%20Preferred%20Roamer/Action/add-operator-action.jsp?action=add&opCountry=CAN&opName=can2&opCC=456&opNDC=6325&opMCC=156&opMNC=0036&sid=0.6507964352578459 HTTP/1.1
Host: 172.16.7.49:8080
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3
Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Proxy-Connection: keep-alive
Referer: http://172.16.7.49:8080/OmniPreferedRoaming/Omni%20Preferred%20Roamer/add-operator.jsp
Cookie: JSESSIONID=5692686F83690546771C7B1E7B6B02DF
Proxy-Authorization: Basic cnBqYW5ha2E6YTdoMzEkNW0=
Pragma: no-cache
Cache-Control: no-cache


The following error was encountered:

* Invalid Request

Some aspect of the HTTP Request is invalid. Possible problems:

* Missing or unknown request method
* Missing URL
* Missing HTTP Identifier (HTTP/1.0)
* Request is too large
* Content-Length missing for POST or PUT requests
* Illegal character in hostname; underscores are not allowed

Hi,

Could you post some of your code?

The error message is quite detailed.. have you checked those suggestions?

function sendRequest(url){
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("Your browser does not support AJAX!");
return;
}
url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("POST",url,true);
xmlHttp.send(null);
}

function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
}
}

the above are the cord used,

* Missing or unknown request method
* Missing URL
these two could not be happend..

* Request is too large
this is also not be a reason because, the page contain several number of data fields, that is like a normal web page

Your code seems ok to me except that it doesn't allow you to send HTTP POSTs the right way.

In a HTTP POST, parameters should be in the HTTP Body, not in the URI. The error message shows parameters are being appended to the URI.

POST /OmniPreferedRoaming/Omni%20Preferred%20Roamer/Action/add-operator-action.jsp?action=add&opCountry=CAN&opName=can2&opCC=456&opNDC=6325&opMCC=156&opMNC=0036&sid=0.6507964352578459 HTTP/1.1

I don't think it really matters if its in the URI though. You just have to make sure each parameter is urlencoded if you place it in the URI.

Heres an example taken from a larger class/object:

/**
* encode passed http vars
*/
fwd_XHR.prototype.encode = function(uri) {
    if (encodeURIComponent) {
        return encodeURIComponent(uri);
    }
    if (escape) {
        return escape(uri);
    }
    return uri;
};

/**
* dencode passed http vars
*/
fwd_XHR.prototype.decode = function(uri) {
    uri = uri.replace(/\+/g, ' ');

    if (decodeURIComponent) {
        return decodeURIComponent(uri);
    }
    if (unescape) {
        return unescape(uri);
    }
    return uri;
};

If you append parameters to the HTTP body in a HTTP POST, you should also specify the Content-Type header as "application/x-www-form-urlencoded". Assuming you want it to be parsed by the server into HTTP POST parameters.

Try something like:

function sendPOST(url, data){
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("Your browser does not support AJAX!");
return;
}
data += "&sid="+encodeURIComponent(Math.random());
xmlHttp.open("POST",url,true);
xmlHttp.onreadystatechange=stateChanged;

xmlHttp.setRequestHeader("Method", "POST "+url+" HTTP/1.1");
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

// one of the error message suggestions is to include content-length header. so try that...
xmlHttp.setRequestHeader("Content-Length", encodeURIComponent(data.length));

xmlHttp.send(data);
}

Call it like:

// the uri has to be url encoded
url = '/OmniPreferedRoaming/Omni%20Preferred%20Roamer/Action/add-operator-action.jsp';

// so does each param value
data = 'action='+encodeURIComponent('add');
data += '&opCountry='+encodeURIComponent('CAN'); // etc.

Also note I included the content-length header which is suggested in teh error message.

Don't think this is related but in the code:

xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("POST",url,true);
xmlHttp.send(null);

you might want to change to:

xmlHttp.open("POST",url,true);
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.send(null);

(I think there is a problem that arises in one of the browsers where the xmlhttprequest resets the object when you call the "open" method - but that might be in IE)

this error is only reported with the Mozilla browser, when it use IE, there is no error and AJAX functions are working properly...

what could be the reason for that...?

this error is only reported with the Mozilla browser, when it use IE, there is no error and AJAX functions are working properly...

what could be the reason for that...?

It may be that Firefox is not sending the HTTP request at all. From the error message it looks like firefox checks against a few rules to see if the HTTP Request is valid, and if it isn't, it gives the error you see...

You may want to try downloading the Firefox Extension called Firebug (if you haven't).

Firebug Dev site: http://www.getfirebug.com/

Once installed an enabled you will be able to view all the HTTP Requests made by firefox. You can filter to view only the "XHR" - XML HTTP Requests.

See if the XHR Request is being sent or not.

BTW: Did you try sending the Content-Length HTTP Request Header?

xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

Digital Ether, you saved me from pulling my hair out.

I was trying to work on my website at a different location and Firefox would not properly handle my http requests, even though it works fine at home.

Forgetting that I had Firebug installed at home I couldn't figure out why I could not find the GET and POST data I was looking for.

After reading your post I installed Firebug to see if I could get to the information and solve the problem, but just installing Firebug fixed the problem!

While this is great for me I am concerned about the users of my web app.

Here is the HTTP request object I got from somewhere, I can't remember where. (I am new at this AJAX stuff)

function HttpClient() { } // HTTPCLIENT CLASS
HttpClient.prototype = {
	// type GET,POST passed to open
	requestType:'GET',
	// when set to true, async calls are made
	isAsync:true,
	// where an XMLHttpRequest instance is stored
	xmlhttp:false,
	// what is called when a successful async call is made
	callback:false,
	// what is called when send is called on XMLHttpRequest
	// set your own function to onSend to have a custom loading
	// effect
	onSend:function()
	{
		//document.getElementById('HttpClientStatus').style.display = 'block';
	},
	
	// what is called when readyState 4 is reached, this is
	// called before your callback
	onload:function()
	{
		//document.getElementById('HttpClientStatus').style.display = 'none';
	},
	
	// what is called when an http error happens
	onError:function(error)
	{
		alert(error);
	},
	
	// method to initialize an xmlhttpclient
	init:function()
	{
		try
		{
			// Mozilla / Safari
			this.xmlhttp = new XMLHttpRequest();
		}
		catch (e)
		{
			// IE
			var XMLHTTP_IDS = new Array('MSXML2.XMLHTTP.5.0',
				 'MSXML2.XMLHTTP.4.0',
				 'MSXML2.XMLHTTP.3.0',
				 'MSXML2.XMLHTTP',
				 'Microsoft.XMLHTTP');
			var success = false;
			for (var i=0;i < XMLHTTP_IDS.length && !success; i++)
			{
				try
				{
					this.xmlhttp = new ActiveXObject
					(XMLHTTP_IDS[i]);
					success = true;
				}
				catch (e)
				{}
			}
			if (!success)
			{
				this.onError('Unable to create XMLHttpRequest.');
			}
		}
	},
	// method to make a page request
	// @param string url  The page to make the request to
	// @param string payload  What you're sending if this is a POST
	//                        request
	makeRequest: function(url,payload)
	{
		if (!this.xmlhttp)
		{
			this.init();
		}
		this.xmlhttp.open(this.requestType,url,this.isAsync);
		
		// set onreadystatechange here since it will be reset after a
		//completed call in Mozilla
		var self = this;
		this.xmlhttp.onreadystatechange = function()
		{
			self._readyStateChangeCallback();
		}
		if (this.requestType == "POST")
		{
			this.xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			this.xmlhttp.setRequestHeader("Content-length", payload.length);
			this.xmlhttp.setRequestHeader("Connection", "close");
		}
		
		this.xmlhttp.send(payload);
		
		if (!this.isAsync)
		{
			return this.xmlhttp.responseXML;
		}
	},
	
	// internal method used to handle ready state changes
	_readyStateChangeCallback:function()
	{
		switch(this.xmlhttp.readyState)
		{
			case 2:
				this.onSend();
				break;
			case 4:
				this.onload();
				if (this.xmlhttp.status == 200)
				{
					this.callback(this.xmlhttp.responseXML);
				}
				else
				{
					this.onError('HTTP Error Making Request: ' + '[' + this.xmlhttp.status + ']' + ' ' + this.xmlhttp.statusText);
				}
				break;
		}
	}
}

And the offending call:

function set_dynamic_globals()
{
	client.requestType = "GET";
	
	client.callback = function(XMLresult)
	{
		
		if (XMLresult.getElementsByTagName("status"))
		{
			http_status = XMLresult.getElementsByTagName("status")[0].childNodes[0].nodeValue;
			
		}else{
			http_status = "FAILED";			
			return;
		}
		if (http_status == "SUCCESS"){
			// bunch of code that reads the values from the XML doc
		}
	}
	client.makeRequest(url,null);
	return;
}

This call does not actually send anything, the target is a PHP created XML doc that contains values read from a database.
Do you see anything wrong with this that would cause Firefox (without Firebug) to fail while IE 6 and IE 7 worked fine?

Much thanks!!

Just wanted to add that when I got home I tested on another PC (other than my main PC) running Linux with Firefox 2.0.0.6 and had the same problem with the http requests, I installed and enabled Firebug and it all started working.

So I am kind of curious what Firebug is doing to Firefox that is making it work where it otherwise would not.

It looks ok to me. That would be odd that Firebug actually makes a difference.

Do you get an error message with that last bit of code or does it just not send a XHR?

I assume url and client are globals. What is the value of url?

You should put some alert()'s into the code to see how far the XHR goes and than quits...

Yes client and url are global.

I did put some alerts in and got as deep as the call to the internal onreadystatechange method.
I could get no errors generated from the class either, best I can tell is it got stuck between ready states???

Not sure if it has any bearing on this, but outside the prototype, where an instance of HttpClient is created:

var client = new HttpClient();

I set client.isAsync to false to halt the js execution until I get my results back.

This app is just for office use, not public use, but I know some of the users do use Firefox so I added an alert specifically for this condition telling them to install Firebug... LOL Oh, I was nice and gave them to url to the download too :)

Yes client and url are global.

I did put some alerts in and got as deep as the call to the internal onreadystatechange method.
I could get no errors generated from the class either, best I can tell is it got stuck between ready states???

Not sure if it has any bearing on this, but outside the prototype, where an instance of HttpClient is created:

var client = new HttpClient();

I set client.isAsync to false to halt the js execution until I get my results back.

This app is just for office use, not public use, but I know some of the users do use Firefox so I added an alert specifically for this condition telling them to install Firebug... LOL Oh, I was nice and gave them to url to the download too :)

Try to see what readyState and http status code you get in the internal onreadystate handler.
If you're using XHR synchronously then the XML response will be returned by the caller of makeRequest(url,null);

So you could do:

client.callback(client.makeRequest(url,null));

on your second last line of custom code.

I have no idea why the readystates are not triggered properly in synchronous XHR.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.