4

I'm trying to see what is my RemoteAction result however the page reloads before it happens.

How can I stop this?

VF Page:

<button class="btn-enter-panel" onclick="getRemoteName()">enter <i class="fa fa-long-arrow-right"></i></button>

JS Code:

<script type="text/javascript">
    function getRemoteName() {
        var fieldContent = $('.elementClassId').val();

        Visualforce.remoting.Manager.invokeAction(
            '{!$RemoteAction.MyController.searchName}'
            ,fieldContent
            ,function(result, event){
                if (event.status) {
                    if(result != null){
                        console.log('result');
                        console.log(result);
                        //do something
                    }
                    else
                    {
                        console.log('Here I am not');
                    }
                } else if (event.type === 'exception') {
                    console.log('exception');
                } else {
                    console.log('Beyond exception');
                }
            }
            , {escape: true}
        );
    }
</script>

I've tried to follow this link JavaScript remoting reloading page but did't fit to my problem or I missunderstand how to apply in my case

1
  • you need to prevent default.-> function getRemoteName(event) { event.preventDefault(); var fieldContent = $('.elementClassId').val(); Commented Oct 23, 2018 at 18:29

2 Answers 2

7

By default, a button will cause a form submit. You have to prevent this default either by cancelling the default behavior, or by returning "false" from your handler. The easiest method is to simply do this:

<button onclick="getRemoteName(); return false;" ...

This will prevent the default behavior from happening, and your function should be called.

1
  • Thanks @sfdcfox That worked, I tried to use event.preventDefault(); before, but that was inside my getRemoteName function, so did't work, now makes sence
    – M. Massula
    Commented Oct 23, 2018 at 19:06
2

The page is reloading because browser is interpreting it as submit button. Default behaviour of submit button is to refresh. You can use the answer suggested by sfdcfox or can try the following:

You can make the type attribute of your button as "button". Some browsers act like submit if type is not specified.

<button class="btn-enter-panel" onclick="getRemoteName()" type="button">enter <i class="fa fa-long-arrow-right"></i></button>

Always specify the type attribute for a element. Different browsers use different default types for the element.

Src: https://www.w3schools.com/tags/tag_button.asp

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .