Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AJAX XMLHttpRequest POST

I'm trying to write an XMLHttpRequest using the POST method. I have managed to use XMLHttpRequest in the past using the GET method but am struggling with POST.

Here's my code:

var xmlhttp = null;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp = new XMLHttpRequest();
}
else
{// code for IE6, IE5
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}

var url = "http://www.mysite.com/script.php";
var params = "var=1";
xmlhttp.open("POST", url, true);
xmlhttp.send(params);

It basically calls a PHP script which then adds some information to a database.

like image 905
diggersworld Avatar asked Nov 25 '10 10:11

diggersworld


People also ask

How do I POST in XMLHttpRequest?

The XMLHttpRequest method send() sends the request to the server. If the request is asynchronous (which is the default), this method returns as soon as the request is sent and the result is delivered using events. If the request is synchronous, this method doesn't return until the response has arrived.

Does AJAX use XMLHttpRequest?

XMLHttpRequest is used heavily in AJAX programming. Despite its name, XMLHttpRequest can be used to retrieve any type of data, not just XML. If your communication needs to involve receiving event data or message data from a server, consider using server-sent events through the EventSource interface.

Is XMLHttpRequest same as AJAX?

XHR is the XMLHttpRequest Object which interacts with the server. Ajax technique in the nutshell leverages the XHR request to send and receive data from the webserver. This object is provided by the browser's javascript environment. It transfers the data between the web browser and server.

How is the XMLHttpRequest object used in AJAX?

The XMLHttpRequest object can be used to exchange data with a server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.


1 Answers

You forgot to explicitly set to Content-type header, which is necessary when doing POST requests.

xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

Also, do not forget to use encodeURIComponent to properly encode your parameters, e.g.:

var params = "var=" + encodeURIComponent("1");

(in this particular example, it's not necessary, but when using special characters like + things will go horribly wrong if you don't encode the parameter text).

Update – you should also replace all instances of %20 with +, like

var params = params.replace(/%20/g, '+');
like image 181
Marcel Korpel Avatar answered Oct 16 '22 20:10

Marcel Korpel