TransWikia.com

JS working when used normally but not in wordpress

WordPress Development Asked on December 19, 2021

I have a shortcode that prints a simple form, a button is used to submit the form. The problem is that when it’s pressed, the form gets submitted normally, ignoring the js function. I can’t understand why it’s doing this, since trying this locally on XAMPP works (I needed to change something to adapt the js code to WP, but nothing that should change its behavior.

This is the code of the function that returns the form markup (called by the add_shortcode‘s callback function, if needed, I’ll add it here)

function print_btn($userid, $category){
    return '<form id="favoritefrm" action="' . FAVORITES__PLUGIN_DIR . 'favorite_fn.php" method="POST"><input type="hidden" name="userid" id="userid" value="' . get_current_user_id() . '"/><input type="hidden" name="category" id="category" value="' . get_the_category(get_the_ID())[0]->name . '"/><button type="submit" id="heart" class="button-heart" style="[...]"></div></form>';
    }

My plugin’s main file enqueues the required styles/scripts this way

function aifavorites_enqueue_style() {
    $btnstyles = plugins_url( 'css/btn_styles.css', __FILE__ );
    wp_enqueue_style('btncss', $btnstyles, false);
}
 
function aifavorites_enqueue_script() {
    $favbtnscript = plugins_url( 'js/fav_btn.js', __FILE__ );
    wp_enqueue_script('mojs', 'https://cdn.jsdelivr.net/mojs/latest/mo.min.js', array('jquery'), true);
    wp_enqueue_script('jquery');
    wp_enqueue_script('favjs', $favbtnscript, array('jquery', 'mojs'), true);
    wp_localize_script('favjs', 'myScript', array(
    'pluginsUrl' => FAVORITES__PLUGIN_DIR,
));
}
 
add_action( 'wp_enqueue_scripts', 'aifavorites_enqueue_style' );
add_action( 'wp_enqueue_scripts', 'aifavorites_enqueue_script' );

The js file that’s giving me problems has the following content:

jQuery( document ).ready(function() {
var scaleCurve = mojs.easing.path('M0,100 L25,99.9999983 C26.2328835,75.0708847 19.7847843,0 100,0');
   var el = document.querySelector('.button-heart'),
    // mo.js timeline obj
    timeline = new mojs.Timeline(),

    // tweens for the animation:

    // burst animation
    tween1 = new mojs.Burst({
        parent: el,
  radius:   { 0: 100 },
  angle:    { 0: 45 },
  y: -10,
  count:    10,
   radius:       100,
  children: {
    shape:        'circle',
    radius:       30,
    fill:         [ 'red', 'white' ],
    strokeWidth:  15,
    duration:     500,
  }
    });


    tween2 = new mojs.Tween({
        duration : 900,
        onUpdate: function(progress) {
            var scaleProgress = scaleCurve(progress);
            el.style.WebkitTransform = el.style.transform = 'scale3d(' + scaleProgress + ',' + scaleProgress + ',1)';
        }
    });
        tween3 = new mojs.Burst({
        parent: el,
  radius:   { 0: 100 },
  angle:    { 0: -45 },
  y: -10,
  count:    10,
   radius:       125,
  children: {
    shape:        'circle',
    radius:       30,
    fill:         [ 'white', 'red' ],
    strokeWidth:  15,
    duration:     400,
  }
    });

// add tweens to timeline:
timeline.add(tween1, tween2, tween3);


// when clicking the button start the timeline/animation:
jQuery("#favoritefrm").on("submit",function(e){
    alert("submitted");
    e.preventDefault();
    var href = myScript.pluginsUrl + '/aifavorites/favorite_fn.php';
    if (jQuery('#heart').hasClass('active')){
        jQuery.ajax({
                   type: "POST",
                   url: href,
                   data: jQuery('#favoritefrm').serialize() + "&action=remove",
                   success: function(msg){
                    alert('submitted');
                    jQuery('#heart').removeClass('active')                         }
                 })
    }
    else{
        jQuery.ajax({
                   type: "POST",
                   url: href,
                   data: jQuery('#favoritefrm').serialize() + "&action=add",
                   success: function(msg){
                    alert('submitted');
                    timeline.play()
                    jQuery('#heart').addClass('active')                         }
                 })
    }
});
});

the jQuery( document ).ready function gets called successfully, I tried putting an alert just below it and it showed up immediately. All the required scripts are loaded, I manually checked both by searching it in Inspect Element "Element" and "Source" tabs (according to how Opera Browser calls them).

What should happen can be seen on my non-wordpress website here

What am I doing wrong? (I know that solving this issue, there’s ajax to handle, but I’m struggling to understand how to convert my code to wp ajax, and it would be great if you could help me with that too)

Thank you in advance to everyone.

One Answer

Solved.

The problem was that mojs has to be included between the <body></body> tags, and the wp_enqueue_script() function that enqueued mojs needed an empty string as argument just before the 'true' parameter (I forgot to specify that there was no required version number of that script).

So, changing

wp_enqueue_script('mojs', 'https://cdn.jsdelivr.net/mojs/latest/mo.min.js', array('jquery'), true);
wp_enqueue_script('favjs', $favbtnscript, array('jquery', 'mojs'), true);

to

wp_enqueue_script('mojs', 'https://cdn.jsdelivr.net/mojs/latest/mo.min.js', array('jquery'), '', true);
wp_enqueue_script('favjs', $favbtnscript, array('jquery', 'mojs'), '', true);

did the trick.

Answered by Kiro on December 19, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP