Question

When coding some JavaScript to send a POST (instead of a GET) back to the webserver, I wondered whether you need to define the XMLHttp.onreadystatechange? My code so far looks like this:

XMLHttp.onreadystatechange = function(){};
XMLHttp.open("POST", "http://something.com/receiver.php", true);
XMLHttp.setRequestHeader("Content-type", "text/plain");
XMLHttp.send("blabla");

because I don't need to do anything when the POST has succeded, and so don't need any functionality to be triggered.

Question 1: I want to make the code as short as possible, and I've thought about setting onreadystatechange = null, anybody knows whether this would work (in all browsers)?

Question 2: I guess it wouldn't be safe to leave onreadystatechange undefined altogether... it might have a predefined value on some systems... anybody knows about this?

Thanks guys!

Was it helpful?

Solution

Actually, instead of setting onreadystatechange to null, you can just leave it out, and nothing will happen.

OTHER TIPS

You'd need it to know if the request is finished or not. Only after that are you supposed to poll for the XHR status.

Because the request might fail intermediately (especially if it fails to arrive at destination, you won't know. If it times out, then it's a failure).

Unless your original plan is to just send a request and forget about it. In that case, you don't need onreadystatechange.

EDIT: or you can use false for its async property. Then XMLHttpRequest.send() will not return until you get a status.

ref: https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/Using_XMLHttpRequest

I know its not what you asked, but since you only need to send a post request and ignore results, I would recommend using a very handy jQuery function. It takes care of all the XMLHTTP things for you:

$.post("test.php", { name: "John", time: "2pm" } );

Consists of url and data you are sending.

Here is further refference: http://api.jquery.com/jQuery.post/

In case its another domain your posting to, simply enable jsonp in the request.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top