How to add a sub menu with AJAX?

As you can’t suppose to get a full working example without any given code, I’ll show you a rough wordpress AJAX setup:

Put all this in functions.php:

<?php
add_action('wp_head', 'my_action_javascript');
function my_action_javascript() {
?>
<script type="text/javascript" >
jQuery(document).ready(function($) {
    jQuery.ajax(
        type: 'POST',
        url: <?php echo admin_url('admin-ajax.php'); ?>,
        data: {
            action : 'your_AJAX_call',
            league : $('input#league').val() // get the user input
        },
        success: function( response, textStatus, XMLHttpRequest ) {
            $('ul#menu').append(response);
        }
        error: function( XMLHttpRequest, textStatus, errorThrown ) {
            alert('An error occured');
        }
    );
});
</script>
<?php
}

add_action( 'wp_ajax_nopriv_your_AJAX_call', 'your_AJAX_call' );
add_action( 'wp_ajax_your_AJAX_call', 'your_AJAX_call' );
function your_AJAX_call() {
    $league = $_POST['league'];
    // do sanitization
    // if sanitization is ok:
        // save to DB
        // echo sth like '<li><a href="https://wordpress.stackexchange.com/questions/50856/new-league">New League</a></li>'
    exit;  // won't work without!
}

I recommend to return a json-encoded array, so you could provide more-detailed information. I.e. if the sanitization fails because it is too short:

// Your sanitization logic here
$arr = array ('success'=>false,'error'=>'Length must be at least 3 Characters');
echo json_encode($arr);

http://php.net/manual/de/function.json-encode.php

Then in your response function of the ajax call:

var response = jQuery.parseJSON(response);
alert('An error occured: ' + response.error);

http://api.jquery.com/jQuery.parseJSON/

Here is a good write-up about using ajax in wordpress:

http://www.garyc40.com/2010/03/5-tips-for-using-ajax-in-wordpress/

EDIT:

Totally forgot about this:

add_submenu_page() won’t work, because the page is already rendered at this point.

Leave a Comment