NicoM
NicoM

Reputation: 619

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 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.

Upvotes: 3

Views: 34972

Answers (2)

Hardmath123
Hardmath123

Reputation: 341

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

Upvotes: 7

Ryan
Ryan

Reputation: 4629

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

$.ajax("http://www.example.com/", {
    type: 'POST',
    data: {
      test: 'test1',
      test2: 'test2'
    }
  })

Upvotes: 1

Related Questions