basickarl
basickarl

Reputation: 40464

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.

Also my server was not hit by the XHR request.

Before:

enter image description here

After:

enter image description here

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?

Upvotes: 2

Views: 3585

Answers (3)

Raphael M&#252;ller
Raphael M&#252;ller

Reputation: 2200

since you want always have false in the onsubmit attribute, you could improve the code like this:

<form onsubmit="test(this); return false;">

with this change in place, it's also semantically better to return true when everything went fine inside your xhr request. (if you want to use the function to send data in another place also.)

so your javascript becomes:

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

        xhr.open('POST', '127.0.0.1:3000/test', true);
        xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
        xhr.send(JSON.stringify({
           url: form.url.value
        }));

        xhr.onloadend = function() {
            // done
        };
    }catch(err){
        return false;
    }

    return true;
}

Upvotes: 0

Quentin
Quentin

Reputation: 943569

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

Upvotes: 1

user6241578
user6241578

Reputation:

if you place an input of type submit inside form tag it will reload. otherwise change it to a button and run the function on button click

<form>
    url:<br>
    <input type="text" id="url" name="url"><br>
    <button>Submit</button>
</form>

Upvotes: 0

Related Questions