Support » Developing with WordPress » Ajax not working

  • Resolved infinityart

    (@infinityart)


    I am using wordpress 4.9.8 with PHP 7.2.6 with the theme Joints-WP and I can’t get ajax to work properly, I get a 400 bad request error. I have searched some post how to set it up, but i can’t get it to work what am i doing wrong?

    This is my PHP code

    function site_scripts() {
        wp_enqueue_script( 'sitejs', get_template_directory_uri() . 
        '/assets/scripts/scripts.js', array( 'jquery' ), filemtime(get_template_directory() 
        . '/assets/scripts/js'), true );
    
         wp_localize_script('sitejs', 'ajaxurl', admin_url('admin-ajax.php'));
    
    }
    
    function ajaxHandler(){
    	echo '<p>test</p>';
    	wp_die();
    }
    add_action('wp_enqueue_scripts', 'site_scripts', 999);
    add_action( 'wp_ajax_my_ajaxHandler', 'ajaxHandler' );
    add_action( 'wp_ajax_nopriv_ajaxHandler', 'ajaxHandler' );

    and here is my javascript code

    jQuery.ajax({
            type: 'POST',
            url: ajaxurl,
            dataType: "html",
            data: {
                'action': 'ajaxHandler',
                'data': 'foo'
            },
            success: function (msg) {
                console.log(msg);
    
            },
            error: function(jqXHR, textStatus, errorThrown){
                console.log(jqXHR, textStatus, errorThrown);
            }
        });
    
        jQuery( document.body ).trigger( 'post-load' );
    • This topic was modified 2 years, 3 months ago by infinityart.
    • This topic was modified 2 years, 3 months ago by bcworkz. Reason: code fixed
Viewing 3 replies - 1 through 3 (of 3 total)
Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Ajax not working’ is closed to new replies.