Connect Http Post Request to an Onclick Using Javascript

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 . 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("").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()>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.

3

2 Answers

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
);
2

If you can include the JQuery library, then I'd suggest you look in to the jQuery .ajax() method ():

$.ajax("", {
    type: 'POST',
    data: {
      test: 'test1',
      test2: 'test2'
    }
  })

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Marcus Vance

Marcus Vance

Cybersecurity & Digital Privacy Researcher

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.

Share this article
Twitter Facebook Pinterest