This is my compontent

<aura:component controller="ccContactController">
        <button onclick="{!c.dothisthing}">do this thing</button>

This is my lightning controller

    dothisthing : function(component, event, helper) {

        var action = component.get('c.goToTheServer');
        action.setCallback(this, function(response) {
            if(response.getState() === 'SUCCESS') {

            } else {
                alert('error = ' + JSON.stringify(response.getError()));

This is my apex controller class

public with sharing class ccContactController {

    public static void goToTheServer()

If I run the the component and press the button I get 'error = Disconnected or Cancelled' and my page is automatically refreshed. If I put the button element outside the form element I get 'success'.

EDIT: Also wanted to say I'm using lightning out. Didn't test in other environments. When I use a div instead of a button the onclick works as expected.

Why can't I have an onclick on a button element inside a form element?



<button /> without type="button" inside a form triggers submit action when clicked. So all you have to do is add the type="button" to the button tag.

 <button type="button" onclick="{!c.dothisthing}">do this thing</button>

Also have a look at the post here it will help.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.