Reputation: 27
I'm trying to call a function using ajax in a wordpress admin submenu. Here is my code.
jQuery('#deleteProj').submit(ajaxSubmit);
function ajaxSubmit(){
var tobeDeleted = jQuery(this).serialize();
alert(tobeDeleted);
jQuery.ajax({
type:"POST",
url: ajaxurl,
data: tobeDeleted,
success:function(){ alert(tobeDeleted);},
error:function(errorThrown){alert(errorThrown);}
});
return false;
}
However, the code opens a new page querying the admin.php file looks like this:
wp/wp-admin/admin.php?q=id&action=deleteproj
I'm really at a loss for why this is happening. I'm calling the function from inside my plugin's admin menu
Update
The issue turned out to be that I had to define the php functions on the main file of my plugin. I also made sure to absolutely define the location of admin-ajax.php this allowed the jQuery to properly execute.
Upvotes: 1
Views: 2909
Reputation: 3663
If you have written the code in side your php file, then the answer from Gulshan is correct, but if you have written this code in a different .js file you can not access the ajax url into it. Then you need to localize the script to add the ajax url.
Please follow the example code :
wp_enqueue_script( 'mainscript', get_template_directory_uri() . '/js/main.js', array(), 'v1', true );
wp_localize_script( 'mainscript', 'sitesettings', array('ajaxurl' => admin_url( 'admin-ajax.php' )));
for both the function you need place same handle [ 'mainscript' ], now in your main.js file you need to write the following code :
jQuery('#deleteProj').submit(function() {
var ajaxurl = sitesettings.ajaxurl; // here you are accessing the admin-ajax.php
var formData= jQuery(this).serialize();
jQuery.ajax({
url:ajaxurl,
action:'function_name',
data:formData,
type: "POST",
success: function(data) {
// return
} });
return false;
});
Hope this work for you
Upvotes: 0
Reputation: 32354
It seems like you are redirecting instead of ajaxing ,try changing you submit event to a click event
jQuery('#deleteProj').find('[type="submit"]').click(function(e){
e.preventDefault();
var tobeDeleted = jQuery(this).serialize();
alert(tobeDeleted);
jQuery.ajax({
type:"POST",
url: ajaxurl,
data: tobeDeleted,
success:function(){ alert(tobeDeleted);},
error:function(errorThrown){alert(errorThrown);}
});
});
Upvotes: 0
Reputation: 1104
Try this:
jQuery('#deleteProj').submit(function() {
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
var formData= jQuery(this).serialize();
jQuery.ajax({
url:ajaxurl,
action:'function_name',
data:formData,
type: "POST",
success: function(data) {
// return
}
});
return false;
});
Regards:)
Upvotes: 1