Connect HTTP POST request to an onclick using JavaScript

html, javascript

Solution

You need to use `XMLHttpRequest` (see MDN).

var xhr = new XMLHttpRequest();
xhr.open("POST", url, false);
xhr.onload = // something
document.getElementById("your_button's_ID").addEventListener("click",
    function() {xhr.send(data)},
    false
);

Problem

I am trying to make an HTTP POST request using javascript and connecting it to an onclick event. For example, if someone clicks on a button then make a HTTP POST request to `http://www.example.com/?test=test1&test2=test2`. It just needs to hit the url and can close the connection. I've messed around in python and got this to work. ``` import urllib2 def hitURL(): urllib2.urlopen("http://www.example.com/?test=test1&test2=test2").close hitURL() ``` I have read about some ways to make HTTP requests using JavaScript in this thread JavaScript post request like a form submit, but think it's overkill for what I need to do. Is it possible to just say something like this: ``` <button onclick=POST(http://www.example.com/?test=test1&test2=test2)>hello</button> Or build it in to an event listener. ``` I know that is not anything real but I am just looking for a simple solution that non-technical people can use, follow directions, and implement. I honestly doubt there is something that simple out there but still any recommendations would be appreciated.

Original source

Related problems