...

View Full Version : Resolved AJAX POST Problem



binaryWeapon
11-28-2008, 02:05 PM
I wrote up a very simple function to do AJAX POSTs and GETs. GETs work, but POSTs don't, for some reason. The function is this:


AJAX=function(options){
var request;
try{
// Opera 8.0+, Firefox, Safari
request = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser doesn't support AJAX.");
return false;
}
}
}
// Create a function that will receive data sent from the server
request.onreadystatechange = function(){
if(request.readyState===4){
options.callback(request.responseText);
}
}
if(options.method.toUpperCase()==="POST"){
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
alert("Open: "+((options.params && options.method.toUpperCase()==='GET')?(options.url+"?"+options.params):options.url)+", Send: "+((options.params && options.method.toUpperCase()==="POST")?options.params:null));
request.open(options.method.toUpperCase(), (options.params && options.method.toUpperCase()==='GET')?(options.url+"?"+options.params):options.url, true);
request.send((options.params && options.method.toUpperCase()==="POST")?options.params:null);
}
When I tried to do the POST request without setting the content-type header, nothing happened. But when I set the content-type header, it behaves like a form (I call it from the page edit.php?page=asdf, and when I try the post request it goes to edit.php).

I'm calling the request like this:

AJAX({
url:'save.php',
method:'POST',
callback:function(a){
alert(a);
},
params:params
});

I'm calling it when a form gets submitted, but i have it return false so the form won't submit.

Any ideas appreciated! :)

shyam
11-28-2008, 02:21 PM
perhaps you should also set the Content-Length and Connection headers for the POST

binaryWeapon
11-29-2008, 01:55 AM
Thanks for the reply.

When putting in those two headers, I noticed that I was sending request headers before I actually opened the connection. I fixed this, and that fixed the odd redirect. Everything works now! =)

Thanks for mentioning the other 2 headers, I forgot about them and wouldn't have noticed my error if I hadn't went back to put them in!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum