0

In my html document I have this:

<button onclick="doFunction()" type="submit" ...>Button</button>

The function looks like this:

doFunction() {
    var goToThisUrl = "www.spring_controller_method.com?redirectUrl=this_page";
    window.location.href = goToThisUrl;
}

The the url in the doFunction() is the url of a Java Spring controller method. In that method it manipulates the database and returns a string to redirect to the page it came from: return "redirect:" + redirectUrl.

The problem is that the button doesn't work. When I click the button, the page refreshes but the data in the database isn't manipulated. The reason I know this isn't a problem with the spring controller method is because of two reasons:

  • I have a breakpoint in the controller method and it isn't being hit.
  • When I take the same doFunction() code and run it on the Chrome developer console, the controller method breakpoint is hit, and the data in the database is changed.

Is there any idea as to why this would be happening?

1
  • 3
    I'm guessing your form is submitting (button type="submit"), return false to prevent default action in your function first. Commented Oct 25, 2013 at 17:19

2 Answers 2

4

Remove type submit from button like

<button onclick="doFunction()" type="button" ...>Button</button>

type="submit" is used for form submission that's why onclick not working.

Sign up to request clarification or add additional context in comments.

3 Comments

Just clarifying that changing the type value to "button" (like you did in the answer) is very important . . . if you just remove the type="submit" attribute, it will fall back on the default, which is also "submit". "button" is the only value that has no inherent action associated with it.
I have faced that problem if i remove type attribute from button it works like submit. don't know what was problem. then i replace submit to button.
Yep . . . it's all here in the HTML specs: w3.org/TR/html401/interact/forms.html#h-17.5 - "This attribute declares the type of the button . . . submit: Creates a submit button. This is the default value."
-1

Add return false; to prevent the default form submission.

doFunction() {
    var goToThisUrl = "www.spring_controller_method.com?redirectUrl=this_page";
    window.location.href = goToThisUrl;
    return false;
}

2 Comments

Putting return false; at the very beginning of your function will stop it from hitting any of the other logic in the function.
Yep. :) Alternately, you could do it outside of the function, in the onclick, like this: onclick="doFunction(); return false;"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.