So I have actually read stackoverflow questions about this, but they are somewhat quite old to work with newest version of wordpress.
My end goal is to submit to database some data from my forms but for now ajax response is not working for me. On custom page load in WP all code is loaded so all functions should work. All of this is inside of PHP file for now that why echo is used to create JS scripts. Here's the important part of my code
echo '<button id="ZapisPrace">Save</button>
<script>
jQuery("#ZapisPrace").click(function($){
var data={
action: "addToDB",
info: "nomz"
};
jQuery.post(ajaxurl,data,function(response){
alert("Response was "+ response);
});
});
</script>';
add_action('wp_ajax_addToDB','pridajDoDB');
function pridajDoDB(){
echo '<script>console.log("AAA")</script>';
wp_die();
}
Using current version of WP so variable ajaxurl is pointing to the
/wordpress/wp-admin/admin-ajax.php
No console.log is happening, response is always 0, even when I remove pridajDoDB function or add_action. It's just not triggering the ajax request correctly. Can somebody let me know why? Also I have not used yet functions like wp_localize_script, wp_register_script or wp_enqueue_script because all of this is in one PHP file that's loaded, and I don't need to import jquery as far as I know its default available in WP. I am just learning how to use WP, PHP AJAX and jQuery, so I have still quite a lot to learn.
PS: I am supposed to use the WP way of using ajax.