WordPress jQuery initialize widgets.php area

Hey guys I’m having a huge problem initializing jQuery on the backend of WordPress (widgets.php). I’m building a widget to display some select options that can only be accessed through SOAP, so I had to ajaxify it using admin-ajax.php. Everything works perfectly on the front-end but when it comes to the backend it breaks completely.

function widget_inject() {
echo "<script>
jQuery(document).ready(function($) {
var ajaxurl = '".admin_url('admin-ajax.php')."';
var list_target_id = 'list-target'; //first select list ID
var list_select_id = 'list-select'; //second select list ID
var initial_target_html = '<option value="">Please select category...</option>'; 

$('#'+list_target_id).html(initial_target_html);

$('#'+list_select_id).change(function(e) {

var selectvalue = $(this).val();


$('#'+list_target_id).html('<option value="">Loading...</option>');

if (selectvalue == "") {

   $('#'+list_target_id).html(initial_target_html);
} else {

  $.ajax({url: ajaxurl,
  data: {
        action: 'parentcatajax1',
        parentCat: selectvalue
    },
         success: function(output) {
            //alert(output);
            $('#'+list_target_id).html(output);
        },
      error: function (xhr, ajaxOptions, thrownError) {
        alert(xhr.status + " "+ thrownError);
      }});
    }
});
});</script>";
}
add_action('admin_enqueue_scripts','widget_inject');

^This is what I’m trying. I’ve tried admin-init, admin-head, admin-footer none of them seem to work.
& yeah I have…

Read More
add_action('wp_ajax_nopriv_parentcatajax1', 'parentCatCallback1');
add_action('wp_ajax_parentcatajax1', 'parentCatCallback1');

for my ajax function; it works perfectly on the front end.

I’m at a stand still for a client & can’t figure out what to do.
Any suggestions? Thanks in advance!

Related posts

Leave a Reply

1 comment

  1. Your printing your jQuery before wordpress has initialized jQuery. Wp_enqueue scripts is not the point where it starts printing the scripts onto the page. The below will clear your jQuery not defined error, let me know if there are more errors after this.

    function widget_inject() {
       echo "<script>
                 jQuery(document).ready(function($) {
             alert('ready');//re-enter your code here
                 })(jQuery);
             </script>";
    }
    add_action('admin_print_scripts','widget_inject', 100);//hook= 'admin_print_scripts'