Karl Morrison Karl Morrison - 3 months ago 14
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

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

Before:

enter image description here

After:

enter image description here

Also my server was not hit.

Code:

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

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

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

xhr.open('POST', '127.0.0.1:3000/test', true);
xhr.send(JSON.stringify({
url: form.url.value
}));

xhr.onloadend = function() {
// done
};

return false;
}
</script>


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

Answer

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', '127.0.0.1:3000/test', true);

Comments