st-trigger-button.js
62 lines
| 1 | function st_get_cookie(cookieName) { |
| 2 | const regex = new RegExp(cookieName + '=([^;]+)'); |
| 3 | const cookieValue = document.cookie.match(regex); |
| 4 | return cookieValue ? cookieValue[1] : null; |
| 5 | } |
| 6 | |
| 7 | function st_trigger_ajax(element) { |
| 8 | var button = element; |
| 9 | button.disabled = true; |
| 10 | var form = button.closest("form"); |
| 11 | var formData = new FormData(form); |
| 12 | |
| 13 | var inputTriggerId = button.parentNode.querySelector('input[name="st_trigger_id"]'); |
| 14 | var inputLoadingLabel = button.parentNode.querySelector('input[name="st_loading_label"]'); |
| 15 | var inputClickedLabel = button.parentNode.querySelector('input[name="st_clicked_label"]'); |
| 16 | var inputButtonLabel = button.parentNode.querySelector('input[name="st_button_label"]'); |
| 17 | var inputUserId = button.parentNode.querySelector('input[name="st_user_id"]'); |
| 18 | |
| 19 | var cookiename = 'st_trigger_button_clicked_' + inputTriggerId.value; |
| 20 | var cookie = 'yes_' + inputUserId.value; |
| 21 | var cookieValue = st_get_cookie(cookiename); |
| 22 | |
| 23 | if (cookieValue === null || cookieValue !== cookie) { |
| 24 | button.classList.add('st_trigger_button_loading'); |
| 25 | if (inputLoadingLabel.value !== '') { |
| 26 | button.textContent = inputLoadingLabel.value; |
| 27 | } |
| 28 | var xhr = new XMLHttpRequest(); |
| 29 | xhr.open('POST', st_ajax_object.ajax_url); |
| 30 | xhr.onreadystatechange = function() { |
| 31 | if (xhr.readyState === XMLHttpRequest.DONE) { |
| 32 | if (xhr.status === 200) { |
| 33 | button.classList.remove('st_trigger_button_loading'); |
| 34 | button.disabled = false; |
| 35 | if (inputClickedLabel.value !== '') { |
| 36 | button.textContent = inputClickedLabel.value; |
| 37 | } else { |
| 38 | button.textContent = inputButtonLabel.value; |
| 39 | } |
| 40 | if( xhr.responseText != '' ){ |
| 41 | var response = JSON.parse(xhr.responseText); |
| 42 | const parsed = new URL(response.data); |
| 43 | if (['http:', 'https:'].includes(parsed.protocol)) { |
| 44 | const redirectencodedURL = encodeURI(parsed.href); |
| 45 | try { |
| 46 | const redirectURL = decodeURI(redirectencodedURL); |
| 47 | window.location.href = redirectURL; |
| 48 | } catch (e) { |
| 49 | console.error(e); |
| 50 | } |
| 51 | } |
| 52 | } |
| 53 | } |
| 54 | } |
| 55 | }; |
| 56 | xhr.send(formData); |
| 57 | } else { |
| 58 | if (inputClickedLabel.value !== '') { |
| 59 | button.textContent = inputClickedLabel.value; |
| 60 | } |
| 61 | } |
| 62 | } |