help with AJAX in plugin (500 bad request error)
-
I am getting into plugin development and am currently familiarizing myself with sending data via AJAX.
The goal is to sent a variable that is in my javascript file to my php so that i can store it in the database (currently I only want to echo it out before taking any next step). I created a very simple plugin with help of the wordpress codex and some online tutorials.
However, i keep being unable to get it to work. Every time I sent the AJAX request I get a 500 internal server error and a bad request error.
Can someone help me out with what mistake I’m making in my request and request handling?
// php code <?php /* Plugin Name: ajaxtest */ // Enqueue script.js function simple_ajax_enqueue_script() { wp_enqueue_script('ajax-script', plugin_dir_url(__FILE__) . 'script.js', array('jquery'), '1.0', true); $my_ajax_nonce = wp_create_nonce('ajax_example'); wp_localize_script( 'ajax-script', 'my_ajax_obj', array( 'ajax_url' => admin_url('admin-ajax.php'), 'nonce' => $my_ajax_nonce, ) ); } add_action('wp_enqueue_scripts', 'simple_ajax_enqueue_script'); // Shortcode to display "Hello, world!" function ajax_test_shortcode() { return '<button id="test-ajax-button">Test Ajax</button>'; } add_shortcode('test', 'ajax_test_shortcode'); /** * AJAX handler using JSON */ add_action('wp_ajax_my_tag_count', 'my_ajax_handler'); add_action("wp_ajax_nopriv_my_tag_count", "my_ajax_handler"); function my_ajax_handler__json() { check_ajax_referer('ajax_example'); $datastring = wp_unslash($_POST['sendingdata']); echo $datastring; wp_send_json("data was sent successfully"); }
jQuery(document).ready(function ($) { $('#test-ajax-button').on('click', function (event) { event.preventDefault(); var datastring = "hello world"; $.post(my_ajax_obj.ajax_url, { _ajax_nonce: my_ajax_obj.nonce, action: "my_tag_count", sendingdata: datastring }, function (response) { console.log("Response:", response); }); }); });
Viewing 1 replies (of 1 total)
Viewing 1 replies (of 1 total)
- The topic ‘help with AJAX in plugin (500 bad request error)’ is closed to new replies.