Karl Morrison Karl Morrison - 1 year ago 138
Javascript Question

POST request changing url and refreshing page

I'm trying to create a http post request via JavaScript. However when I click submit the page refreshes and the url is changed.

I return

on the
attribute. So it should not be "submitting" in that sense.


enter image description here


enter image description here

Also my server was not hit.


<form onsubmit="return test(this)">
<input type="text" id="url" name="url"><br>
<input type="submit" value="Submit">

function test(form) {
var xhr = new XMLHttpRequest();

xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');

xhr.open('POST', '', true);
url: form.url.value

xhr.onloadend = function() {
// done

return false;

I can't see when it isn't working?

Answer Source

Open the Console in your browser's developer tools. Read the error message

VM125:5 Uncaught InvalidStateError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED.

Since it throws an exception, it never reaches return false

Move xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8'); so it appears after xhr.open('POST', '', true);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download