Jackson
Jackson

Reputation: 264

Ajax call Not Working in Custom plugin

I am creating a plugin to display all post types in a drop down and another select box to display the corresponding categories (taxonomies) of each post type. When the post type is changed the corresponding categories are selected via an ajax call.

This is my code:

add_action('admin_menu', 'taxonomy_menu');

function taxonomy_menu(){
        add_menu_page( 'Taxonomy Plugin', 'Custom Taxonomy Plugin', 'manage_options', 'custom-taxonomy-plugin', 'tax_settings' );
}
function tax_settings(){
 $url = plugin_dir_url().'cust-taxonomy/ajax_tax.php';
 $taxo = get_taxonomies();
 var_dump($url);
?>
<form method="POST" action="">
 Post Type<select class="taxonomy">
 <?php
 foreach ( get_post_types() as $post_type ) {
 ?>
  <option value="<?php echo $post_type;?>"><?php echo $post_type;?></option>
 <?php } ?>
 </select><br>
 Categories<select>
  <option value="">Select</option>
 </select><br>
 No: of posts<input type="text" name="num_posts"><br><span></span>
 <input type="submit" name="submit" value="submit">
 </form>
<?php 
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
 jQuery(".taxonomy").change(function(){
  var post_type = this.value;
  alert(post_type);
  jQuery.ajax({
            type:'POST',
            url:"<?php echo plugin_dir_url().'cust-taxonomy/ajax_tax.php';?>",
            data: post:post_type,
            success:function(result){
             alert(result);
            }
        });
 });
});
</script>

Here no AJAX call is going to the corresponding URL. Why is that?

Upvotes: 0

Views: 435

Answers (2)

mrchidam
mrchidam

Reputation: 234

I could see that there is a syntax error in the call to jQuery.ajax(). The argument that you are passing is not a proper java script object. You need to enclose post: post_type with curly braces as shown below.

jQuery.ajax({
            type:'POST',
            url:"<?php echo plugin_dir_url().'cust-taxonomy/ajax_tax.php';?>",
            data: {post:post_type},
            success:function(result){
             alert(result);
            }
        });

Upvotes: 1

Elvin Haci
Elvin Haci

Reputation: 3572

You can't use plugin_dir_url without argument. Use this format instead;

plugin_dir_url(__FILE__).'cust-taxonomy/ajax_tax.php';

Upvotes: 0

Related Questions