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

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

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.

  • 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 Oct 23 at 19:06

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

Your Answer

 
discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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