0
votes

I'd like to submit a form and go back to where the user came from using a button in HTML. My button looks like this:

<input type="submit" value="submit" onclick="history.back(-1)" />

The form gets submitted but the onclick doesn't redirect. Is there an easy way to do this or do I need to create a JS function or do something server-side?

3
you should send data by ajax and do history.back(-1). - Sato Takeru
you can use <input type="submit" value="submit" onclick="window.location.href=history.back(-1)"/> - Abhinava B N

3 Answers

0
votes

You should handle your form submission with Ajax, and to prevent browser default behavior do like this:

<input type="submit" value="submit" onclick="handleSubmit()" />
function handleSubmit(e) {

    //prevent default behavior of browser on submit form
    e.preventDefault();
    
    //do your job here
    sendDataToExampleAPI();

    //back to previous address in browser
    window.history.back();
}
0
votes

history.back(-1) you should use window.location.href=history.back(-1) instead

<input type="submit" onclick="window.location.href=history.back(-1)"/> 

You should use it.

Also, don't forget to use e.preventDefault()to prevent unexpected behavior in form submission.

You may also need to submit data with Ajax.

0
votes

history.back() method alone in HTML does not do anything.

You should have a function in JS that calls history.back() and pass that function to your onclick in HTML. Plus, history.back() method does not receive any arguments. It automatically goes 1 step back. Alternatively, you can use history.go(-1).

So, something like this:

<input type="submit" value="submit" onclick="goBack()" />

function goBack() {
  history.back();
}

Check this for reference

Also, to submit the form, your <input> should be inside <form> tag, like this:

<form id="form">
  <input type="submit">Submit form/>
</form>