Home > Software engineering >  Code Executing on Page Load instead of OnClick
Code Executing on Page Load instead of OnClick

Time:11-21

I have a code that gets executed on page load twice, despite adding the code to the ‘Click’ command.

I have placed the code 'alert("Testing");' within the portion of the code pertaining to 'click(function(evt)' - grateful if someone can advise if I misunderstood the functionality of this method, as I assumed code within the subsequent brackets would only execute on button click.

Any insight would be gratefully received.

public static function get_javascript() {

            ob_start();
            ?>
            <script type="text/javascript">

                jQuery(document).ready(function() {
        
                    jQuery('#fpd-share-button').click(function(evt) {
                        alert("Testing");
                        evt.preventDefault();

                        jQuery(".fpd-share-widget, .fpd-share-url").addClass('fpd-hidden');
                        jQuery('.fpd-share-process').removeClass('fpd-hidden');
                        var scale = $selector.width() > 800 ? Number(800 / $selector.width()).toFixed(2) : 1;
                        fancyProductDesigner.getViewsDataURL(function(dataURLs) {

                            var dataURL = dataURLs[0],
                                data = {
                                action: 'fpd_createshareurl',
                                image: dataURL,
                                product: JSON.stringify(fancyProductDesigner.getProduct()),
                            };
                            jQuery.post("<?php echo admin_url('admin-ajax.php'); ?>", data, function(response) {

                                if(response.share_id !== undefined) {

                                    var pattern = new RegExp('(share_id=).*?(&|$)'),
                                        shareUrl = window.location.href;

                                    if(shareUrl.search(pattern) >= 0) {
                                        //replace share id
                                        shareUrl = shareUrl.replace(pattern,'$1'   response.share_id   '$2');
                                    }
                                    else{
                                        shareUrl = shareUrl   (shareUrl.indexOf('?')>0 ? '&' : '?')   'share_id='   response.share_id;
                                    }

                                    //append selected attributes of variable product
                                    var variationsSer = $productWrapper.find('.variations_form .variations select')
                                        .filter(function(index, element) {
                                            return $(element).val() != "";
                                        }).serialize();
                                    if(variationsSer && variationsSer.length > 0) {
                                        shareUrl  = ('&'   variationsSer);
                                    }
                                    <?php
                                        $shares = fpd_get_option('fpd_sharing_social_networks');
                                        $shares = str_replace(',"googleplus"', '', $shares);
                                    ?>
                                    jQuery(".fpd-share-widget").empty().jsSocials({
                                        url: shareUrl,
                                        shares: <?php echo is_array($shares) ? json_encode($shares) : '['.$shares.']'; ?>,
                                        showLabel: false,
                                        text: "<?php echo FPD_Settings_Labels::get_translation( 'misc', 'share:_default_text' ); ?>"
                                    }).removeClass('fpd-hidden');
                                }

                                jQuery('.fpd-share-process').addClass('fpd-hidden');
                                jQuery('.fpd-share-url').attr('href', shareUrl).text(shareUrl).removeClass('fpd-hidden');

                            }, 'json');

                        }, 'transparent', {multiplier: scale, format: 'png'});
                    });
                <?php
                ?>
                });
            </script>
            <?php
            $output = ob_get_contents();
            ob_end_clean();

            return $output;
        }
    }
}

CodePudding user response:

Obviously I can't do a full test on your code, too many parts are missing to reproduce the problem and the whole environment. But I have created a skeleton of the basic structure of what I think you want to achieve. And it seems to work.

You can try the code online here: https://www.w3schools.com/php/phptryit.asp?filename=tryphp_compiler It is the only site I have found that allows you to mix html, js and php.

<?php
    function get_javascript() {
        ob_start();
?>

        <script type="text/javascript">
            jQuery(document).ready(function() {
                jQuery('#fpd-share-button').click(function(evt) {
                    alert("Testing");
                    evt.preventDefault();
                });
            });
        </script>

<?php
        $output = ob_get_contents();
        ob_end_clean();

        return $output;
    }
?>

<!DOCTYPE html>
<head>
<script
  src="https://code.jquery.com/jquery-3.6.0.min.js"
  integrity="sha256-/xUj 3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
  crossorigin="anonymous"></script>

<?php
    echo get_javascript();
?>

</head>
<body>
    <button  id="fpd-share-button">SHARE</button>
</body>

</html>
  • Related