Can’t get AJAX call working in custom plugin

So the AJAX action defined in Myplugin::define_admin_hooks() has been corrected (it’s just a typo in the question).

But there’s another issue in your code, also in the above function, where the second parameter for $this->loader->add_action() should actually be $plugin_admin (which is an object and an instance of the Myplugin_Admin class) and not wp_ajax:

  • Incorrect: $this->loader->add_action( 'wp_ajax_myplugin_ajax_function', 'wp_ajax', 'myplugin_ajax_function' );

  • Correct: $this->loader->add_action( 'wp_ajax_myplugin_ajax_function', $plugin_admin, 'myplugin_ajax_function' );

And I actually noticed another issue — in Myplugin_Admin::myplugin_ajax_function(), I believe you wanted to call the myplugin_do_magic() method/function in the Myplugin_Admin class, so you should use $result = $this->myplugin_do_magic($url); (note the $this->) because otherwise, then you would end up with a 500 internal server error!

Unless of course if for example there’s a function named myplugin_do_magic defined in the global scope.

So make sure that you call a class method properly. =)