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.
Also my server was not hit by the XHR request.
Before:
After:
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?