• Resolved fblanco

    (@fblanco)


    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!

    • This topic was modified 5 years, 8 months ago by fblanco.
Viewing 5 replies - 1 through 5 (of 5 total)
  • I have seen some folks use jQuery.ajax, but mostly jQuery.post, like this

    jQuery(document).ready(function($){
    	var data = {
    		action: 'notify_button_click',
    		security: ajax_test_vars.ajaxnonce,
    		message: "Button has been clicked!"
    	};
    	$.post(ajax_test_vars.ajaxurl, data, function(response) {
    		alert("Response: " + response);
    	});
    });

    In my theme code that uses AJAX, it is for the Customizer, so it uses wp.ajax.post() because the nonce is tied in with the Customizer.
    In a plugin I was writing for the front end, it is for files, so I use the FormData() object, and the vanilla XMLHttpRequest(), but for other data, I use jQuery.post().
    You might have a problem on the PHP side, though, if you have your code in the theme or in a helper plugin that might not load it when you need it loaded.
    I suggest you make your own plugin file with your code. The “Bad Request” could be that the action was not registered, meaning your PHP code didn’t run.

    The wp_localize_script call is for WP to output your variables in JS, so your script knows the address to POST the AJAX call to. It is meant for translations to pass to JS, but you can pass any data. More recently, there is another way to do JS translation strings.

    Thread Starter fblanco

    (@fblanco)

    Thanks for answering!

    Just using jQuery.post instead of ajax apparently worked. I have no idea why hahaha. Would you happen to know what difference it makes?

    • This reply was modified 5 years, 8 months ago by fblanco.

    No, I haven’t studied the details of the jQuery internals.

    Moderator bcworkz

    (@bcworkz)

    .post() will serialize its data so PHP will properly handle the passed data. .ajax() doesn’t do so for simple JS arrays or objects, so PHP does not “see” the passed data as expected. Hence the bad request. To use .ajax(), pass your object through jQuery.param().

    Why ever use .ajax() then? It works well with form data. Just be sure you have a hidden field named “action” whose value WP uses to construct an action hook tag name.

    Thread Starter fblanco

    (@fblanco)

    This has been very helpful! Thanks to you both!

Viewing 5 replies - 1 through 5 (of 5 total)

The topic ‘Using AJAX’ is closed to new replies.