JQuery Ajax Callback Is Either Not Triggered or Not Working

I just started experimenting with jQuery and ajax. I have looked through similar posts but I am still unable to resolve my issue.

So here goes, I am writing a wordpress plugin. I have the following:

 add_action('wp', 'wl_init');

 add_action('wp_ajax_wl_add_wishlist', 'wl_wishlist_process');
 add_action('wp_ajax_nopriv_wl_add_wishlist', 'wl_wishlist_process');

 function wl_wishlist_process (){
    echo 'test';
    die();
 }

  function wl_init(){
      wp_register_script( 'wishlist-js', plugins_url( '/wishlist.js', __FILE__ ), array('jquery') );

      wp_localize_script( 'wishlist-js', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));

      wp_enqueue_script( 'jquery');
      wp_enqueue_script( 'wishlist-js' );
  }

And this is my js file"

jQuery(document).ready(function($) {
        $('#wl_wishlist').click(function(e) {
            alert('This runs');
            //var plugurl = document.location.protocol+'//'+document.location.host+'/test/wp-admin/admin-ajax.php';
            //"<?php echo admin_url('admin-ajax.php'); ?>"
            //"/test/wp-admin/admin-ajax.php"
            jQuery.ajax({url: myAjax.ajaxurl, type: 'post', data: {action: 'wl_wishlist_process', post_id:100}, success: function(response) {
                alert(response);
            },
            error : function (xhr){
                alert('There is an error');

            }});

        });
});

I know the js file is loaded and running as I see the alert('This runs'). However, it neither gives me success nor error. Is it error with the ajax call or is it the callback function error? What am I missing here?

Also, When I open the url of the ajax call (), it shows '0'. Is this correct?

I have used all the commented methods to get the url, but none works.

Thanks!

2
David Miller

David Miller

Executive Financial & Market Analyst

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.

Share this article