From bb894daecc4bffd40c96a93704476948645adfbc Mon Sep 17 00:00:00 2001 From: Jakub Boukal Date: Tue, 3 Sep 2024 19:08:50 +0200 Subject: [PATCH] Fix: Handle undefined `django` object to prevent TypeError. Fixes: #313 - Added a check to ensure `django` is defined before accessing `django.jQuery`. - This prevents the "Uncaught TypeError: Cannot read properties of undefined (reading 'jQuery')" error. --- .../static/ajax_select/js/ajax_select.js | 44 ++++++++++--------- 1 file changed, 23 insertions(+), 21 deletions(-) diff --git a/ajax_select/static/ajax_select/js/ajax_select.js b/ajax_select/static/ajax_select/js/ajax_select.js index 9ac063aa3e..059cd50bc4 100644 --- a/ajax_select/static/ajax_select/js/ajax_select.js +++ b/ajax_select/static/ajax_select/js/ajax_select.js @@ -231,25 +231,27 @@ * In django >= 1.10 we could try to rely on input.trigger('change') * and avoid this hijacking, but the id and repr isn't passed. */ - djangoJQuery(document).ready(function () { - var djangoDismissAddRelatedObjectPopup = - window.dismissAddRelatedObjectPopup; - if (!djangoDismissAddRelatedObjectPopup) { - throw new Error("dismissAddAnotherPopup not found"); - } - - window.dismissAddRelatedObjectPopup = function (win, newId, newRepr) { - // Iff this is an ajax-select input then close the window and - // trigger didAddPopup - var input = $("#" + win.name.replace("__1", "")); - if (input.length && input.data("ajax-select")) { - win.close(); - // note: newRepr is django's repr of object, not the Lookup's formatting of it. - input.trigger("didAddPopup", [newId, newRepr]); - } else { - // Call the normal django set and close function. - djangoDismissAddRelatedObjectPopup(win, newId, newRepr); + if (djangoJQuery) { + djangoJQuery(document).ready(function () { + var djangoDismissAddRelatedObjectPopup = + window.dismissAddRelatedObjectPopup; + if (!djangoDismissAddRelatedObjectPopup) { + throw new Error("dismissAddAnotherPopup not found"); } - }; - }); -})(window.jQuery, window.django.jQuery); + + window.dismissAddRelatedObjectPopup = function (win, newId, newRepr) { + // Iff this is an ajax-select input then close the window and + // trigger didAddPopup + var input = $("#" + win.name.replace("__1", "")); + if (input.length && input.data("ajax-select")) { + win.close(); + // note: newRepr is django's repr of object, not the Lookup's formatting of it. + input.trigger("didAddPopup", [newId, newRepr]); + } else { + // Call the normal django set and close function. + djangoDismissAddRelatedObjectPopup(win, newId, newRepr); + } + }; + }); + } +})(window.jQuery, window.django && window.django.jQuery);