Support » Plugin: WPHelpful » Solution without jQuery

  • Robert

    (@hartlrobert)


    I do not want loading jQuery (+ migrate) just for this function.
    So here is my code with vanilla js.
    Maybe it will help someone or the plugin author includes this in his great plugin. Since then You have to wp_dequeue_script(‘wphelpful’);wp_deregister_script(‘wphelpful’); in your theme’s functions.php.

    You’re welcome.

    var $this;
    document.addEventListener('DOMContentLoaded', function() {
    
        // Determine if we should disable the submit button or show the feedback section on load: 
        var ratings = document.querySelectorAll('.wph .wph-rating');
        ratings.forEach(rating => {
            rating.addEventListener("change", function (e) {
                var checked = [...ratings].filter(el => {
                    return el.checked;
                });
                this.closest('.wph form.wph-form').querySelector('.wph-button').disabled = checked.length < 1;
                if ((document.querySelectorAll('.wph.wph-after_rating').length > 0) && (checked.length > 0)) {
                    document.querySelector('.wph-feedback-wrap').classList.add("fade-in-show");
                    document.querySelector('.wph-feedback-wrap').classList.remove("fade-in-hide");
                }
            });
            var event = document.createEvent('HTMLEvents');
            event.initEvent('change', true, false);
            rating.dispatchEvent(event);
        });
    
        // If we don't show the feedback section, just submit upon rating change:
        var never = document.querySelectorAll('.wph.wph-never .wph-rating');
        never.forEach(elem => {
            elem.addEventListener('change', function(e) {
                var event = document.createEvent('HTMLEvents');
                event.initEvent('submit', true, false);
                var forms = document.querySelectorAll('.wph form.wph-form');
                forms.forEach(form => {
                    form.dispatchEvent(event);
                });
            });
        });
    
        // If we show feedback after rating, show it once we have a rating:
        var afterRating = document.querySelectorAll('.wph.wph-after_rating .wph-rating');
        afterRating.forEach(elem => {
            elem.addEventListener('change', function(e) {
                document.querySelector('.wph-feedback-wrap').classList.add("fade-in-show");
                document.querySelector('.wph-feedback-wrap').classList.remove("fade-in-hide");
            });
        });
    
        var forms = document.querySelectorAll(".wph form.wph-form");
        forms.forEach(form => {
            form.addEventListener("submit", function(e){
                e.preventDefault();
    
                $this = form.querySelector('.wph-button');
    
                var data = {
                    _ajax_nonce: '<?=$nonce?>',
                    action: 'wphelpful_save_feedback'
                };
    
                // add form data to data:
                var formData = serializeArray(form); 
                for (var x in formData) {
                    data[formData[x]['name'].replace('wphelpful[', '').replace(']', '')] = formData[x]['value'];
                }
                data['local_time'] = '' + new Date() + '';
    
                $this.setAttribute('disabled', 'disabled');
    
                // change text to active state from settings...
                //var button_text = $this.html();
                var active_button_text = $this.dataset.active;
                $this.innerHTML = active_button_text;
                
                //console.log(data);
    
                var str = [];
                for(var p in data){
                    str.push(encodeURIComponent(p) + "=" + encodeURIComponent(data[p]));
                }
                str = str.join("&");
    
                var request = new XMLHttpRequest();
                request.open('POST', '/wp-admin/admin-ajax.php', true);
                request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
                request.send(str);
                request.onload = function() {
                    if (this.status >= 200 && this.status < 400) {
                        var respData = JSON.parse(this.response);
                        for (var x in respData) {
                            document.querySelector(''+x).outerHTML = respData[x];
                        }
                    }
                };
                request.onerror = function(e) {
                    $this.setAttribute('disabled', false);
                    $this.innerHTML = 'Error';
                    // TODO: should this be a setting?
                    alert("Uh oh! We ran into an error saving your feedback.");
                    console.log(e);
                };
                return false;
            });
        });
        function serializeArray(form) {
            var field, l, s = [];
            if (typeof form == 'object' && form.nodeName == "FORM") {
                var len = form.elements.length;
                for (var i=0; i<len; i++) {
                    field = form.elements[i];
                    if (field.name && !field.disabled && field.type != 'file' && field.type != 'reset' && field.type != 'submit' && field.type != 'button') {
                        if (field.type == 'select-multiple') {
                            l = form.elements[i].options.length; 
                            for (j=0; j<l; j++) {
                                if(field.options[j].selected)
                                    s[s.length] = { name: field.name, value: field.options[j].value };
                            }
                        } else if ((field.type != 'checkbox' && field.type != 'radio') || field.checked) {
                            s[s.length] = { name: field.name, value: field.value };
                        }
                    }
                }
            }
            return s;
        }
    })
Viewing 1 replies (of 1 total)
  • Thread Starter Robert

    (@hartlrobert)

    Further suggestion:

    • translate yes and no
    • make append_custom_styles removable
Viewing 1 replies (of 1 total)
  • You must be logged in to reply to this topic.