My problem is: Can't do a POST request with jQuery. Down here is the complete description:
I created a link in a page (using the plugin PHP code for posts and pages):
<?php
$nonce = wp_create_nonce("test_nonce");
$link = admin_url('admin-ajax.php?action=my_delete_object&object_id='.$object_id.'&nonce='.$nonce);
echo "<a data-object_id=\"".$object_id."\" data-nonce=\"".$nonce."\" href=\"".$link."\" class=\"delete-object\" >Click Here!</a>
?>
Then I added this to my child theme's functions.php:
wp_enqueue_script( 'js_functions', get_bloginfo( 'stylesheet_directory' ) . '/js/functions.js', array( 'jquery' ), false);
wp_localize_script( 'js_functions', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
add_action("wp_ajax_my_delete_object", "my_delete_object");
add_action("wp_ajax_nopriv_my_delete_object", "my_must_login");
function my_delete_object() {
echo "<script> alert('test: ajax request reached action!') </script>";
// nonce check and other actions;
$result['type'] = "success";
die();
}
function my_must_login() {
//tell user to log in;
$result['type'] = "success";
die();
}
If I click the link, I get the alert ("test: ajax request reached action!") correctly and, if I add other actions to my_delete_object, they take place as well.
The problem started when I wanted to add an ajax request to the scene.
In my child theme's folder, I created the folder js, and put the file functions.js inside with the content:
jQuery(document).ready(function($) {
$(".delete-object").click( function(event) {
event.preventDefault();
object_id = $(this).attr("data-object_id");
nonce = $(this).attr("data-nonce");
$.post({
url : MyAjax.ajaxurl,
data : {action: 'my_delete_object', object_id: object_id, nonce: nonce},
success: function(response) {
if(response.type == "success") {
alert("Ajax request returned success!");
}
else {
alert("Ajax request returned something else.");
}
},
error: function(){
alert("Ajax request no good");
}
});
alert('click triggered action!');
});
});
Then it does nothing when I click the link. It just pops the alert "click triggered action!", and nothing else.
My conclusion is that the POST is not happening. Any ideas why?