2

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.

Community
  • 1
  • 1
NicoM
  • 589
  • 2
  • 5
  • 20
  • http://en.wikipedia.org/wiki/Same-origin_policy – zerkms Dec 01 '13 at 01:08
  • I think you want to close certain connection with javascript by calling a php file in which close connection code is. Am i right? – Airy Dec 01 '13 at 01:24
  • Not necessarily, I work in analytics and want to use a new part of Google Analytics to be able to track interaction with content pieces I have on other sites. The new Google Analtyics let you push data to their servers using HTTP POST requests https://developers.google.com/analytics/devguides/collection/protocol/v1/ – NicoM Dec 01 '13 at 02:02

2 Answers2

3

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
);
Hardmath123
  • 191
  • 9
  • Thanks a lot Hardmath123! This works when i load the page but after I click the button once i get this error "Uncaught InvalidStateError: Failed to execute 'send' on 'XMLHttpRequest': the object's state must be OPENED. off-site-tracking.html:17 (anonymous function)" do you know of a way to alter the code so I can click the button multiple times? Thanks again! – NicoM Dec 01 '13 at 01:58
  • If you move lines 1-3 to inside the function() block before the 'xhr.send()', the button should become reusable. – Hardmath123 Dec 01 '13 at 03:32
1

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'
    }
  })
Ryan Nigro
  • 3,751
  • 2
  • 15
  • 23