1

Slightly confused as how to use Ajax in a wordpress plugin.

Do you have to use jQuery as at the moment my code is plain vanilla javascript?

Also I am not sure if I am able to use inline code or do I have to place javascript in separate files so I can use wp_enque?

<?php
/*
 * Plugin Name:  React Test
 * Description:  Simple Reactjs test
 * Version:      0.0.1
 */


/**
 *  Add the plugin to the sub menu
 *  of the admin section
 */
function rt_addToAdminMenu(){
    $page_title = 'React Test';
    $menu_title = 'React Test';
    $capability = 'manage_options';
    $menu_slug  = 'react-test';
    $function   = 'rT_helloWorld';
    $icon_url   = 'dashicons-media-code';
    $position   = 4;

    add_menu_page( 
        $page_title,
        $menu_title,
        $capability,
        $menu_slug,
        $function,
        $icon_url,
        $position 
    );
 }
 add_action('admin_menu', 'rt_addToAdminMenu');


/*
 * This function is called 
 * from the admin menu in the wp dashboard
 */
 function rT_helloWorld(){
     //include the file with html and javascript to keep code cleaner
     //side note : javascript is written inline ie. <script>code here....</script> 
     require_once "test-file.php";
 }


/*
 * This function is called to 
 * handle the ajax request
 */
function rt_handleAjaxPost(){
   echo "Thanks";
   wp_die();
}
add_action( 'wp_ajax_rt_handleAjaxPost', 'rt_handleAjaxPost' );

Here is the javascript which is in the test-file.php, which sends the ajax request

<script>
//some more javascript above
...
buildButton.addEventListener("click", function(){        
    //send this via ajax to php so wordpress can use it in a post a or whereever

    var action  = "<?php echo admin_url('admin-ajax.php'); ?>";
    var data    = {
         action  : "rt_handleAjaxPost",
         test    : "Hello"
    };
    var method  = "post";
    try {
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function(){
            if(xhr.readystate === 4 && xhr.status === 200){
                //do something here
                console.log("success");
                alert("success");
            }
        }
        xhr.open(method, action);
        xhr.send(data);
    } catch (e) {
        console.log(e.message);
    }
});
</script>

I am getting a 400 bad request in the javascript error console when the code is ran.

Any help as how to get this code working and preferably not to use jquery if possible.

Thanks in advance

1
  • Have you considered using WP REST API endpoints instead? You shouldn't need to use jQuery – Tom J Nowell Jan 2 '18 at 22:59
0

Here's a base snippet I use for AJAX submits in Wordpress. It does use jQuery, but there's no reason vanilla won't work.

You could admin_enqueue_scripts() the <script>, and conditionalize it on the proper page with get_current_screen().

add_action( 'admin_menu', function(){
    add_menu_page( 'My Plugin', 'My Plugin', 'manage_options', 'my_plugin_slug', 'my_plugin_page', 'dashicons-cloud' );
});

function my_plugin_page() {
    if (isset($_POST['my_plugin_ajax_submit']))
        if ( wp_verify_nonce( $_POST['nonce'], 'my_plugin_ajax_submit' ) )
            my_plugin_ajax_submit();    
    ?>

    <button id='buildButton'>Do Something</button>

    <script>
        jQuery('#buildButton').click(function(){
            jQuery.ajax({
                type: 'post',
                data: { 
                    "my_plugin_ajax_submit": "now",
                    "nonce" : "<?php echo wp_create_nonce( 'my_plugin_ajax_submit' ); ?>"
                },
                success: function(response) { 
                    jQuery('#buildButton').text("Somthing Done!");
                },
                error: function(response) { 
                    jQuery('#buildButton').text("...error!");
                },
            });
        });
    </script>
    <?php
}

function my_plugin_ajax_submit() {

    // some php code that fires from AJAX click of #buildButton
    wp_mail( 'user@domain.com', 'my_plugin_ajax_submit() fired', time());

    return true;
}
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.