Using AJAX
-
Hello!
I’m fairly new to using ajax in wordpress. I tried following some tutorials but I still can’t get it to work. Right now all I want to do is send a message on the click of a button and then print another message that comes inside the response.This is my JS script:
jQuery(document).ready( function(){ jQuery('#my-button').on('click', function(){ jQuery.ajax({ type : "post", contentType: "json", dataType : "json", url : ajax_test_vars.ajaxurl, data : { action: "notify_button_click", message : "Button has been clicked!", }, error: function(response){ console.log("i messed up"); jQuery('#txtMessage').text(response.res_data); }, success: function(response) { console.log("im fine"); jQuery('#txtMessage').text(response.res_data); } }) }); });Then, in functions.php (I’m using the CodeSnippets plugin for this):
add_action( 'wp_enqueue_scripts', 'ajax_test_js' ); function ajax_test_js() { wp_register_script('ajax_test', get_template_directory_uri(). '/assets/js/test.js', ['jquery'], '1.1', true ); wp_enqueue_script('ajax_test'); wp_localize_script('ajax_test','ajax_test_vars',['ajaxurl'=>admin_url('admin-ajax.php')]); } add_action('wp_ajax_nopriv_notify_button_click','notify_button_click'); add_action('wp_ajax_notify_button_click','notify_button_click'); function notify_button_click(){ wp_send_json(["res_data" => "Im a json response"]); }So far, this returns a Bad Request. Also, I must say that I’m not entirely sure what this part does:
wp_localize_script('ajax_test','ajax_test_vars',['ajaxurl'=>admin_url('admin-ajax.php')]);As I mentioned I’m new to this, so I apologize if my questions are a bit silly. Any help will be greatly appreciated.
Thanks!
The topic ‘Using AJAX’ is closed to new replies.