Output certain text into DIV using Ajax in WordPress

I’m very new to Ajax. Through a lot of trial an error, I have a basic example and I’m looking to expand it.

I’m working on a custom WordPress page with an image map of the USA and I need to use Ajax to fill in a div with information on each state.

Read More

When a user clicks on the map area defined to be New York an href is triggered like:
href="javascript:getStateInfo('newyork')"

Here is my JS function:

function getStateInfo(name)
    {
        var name = this.name;
        jQuery.ajax({
        type: 'POST',
        url: '/wp-admin/admin-ajax.php',
    data: {
        action: name, // the PHP function to run
    },
    success: function(data, textStatus, XMLHttpRequest) {
        jQuery('#infoDiv').html(''); // empty an element
        jQuery('#infoDiv').append(data); // put our list of links into it
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
        if(typeof console === "undefined") {
            console = {
                log: function() { },
                debug: function() { },
            };
        }
        if (XMLHttpRequest.status == 404) {
            console.log('Element not found.');
        } else {
            console.log('Error: ' + errorThrown);
        }
    }
});}

I’m looking to get the information with ajax so in my functions.php file I have

function newyork()
{
    echo 'this is info on new york state';
    die();
}
add_action( 'wp_ajax_nopriv_newyork', 'newyork' );
add_action( 'wp_ajax_newyork', 'newyork' );

Obviously this code doesn’t work, and I’m not even sure if I should be writing 50 different functions with add_action‘s for each state. If anyone knows of a better way to implement this, I’m really eager to learn how to implement this most efficiently?

Related posts

Leave a Reply

1 comment

  1. This is actually really simple and you don’t even need to use aJax at all for this.

    However you define the area for the maps your js can look like this

    $('.state').on('click', function(){
        var state = $(this).val();
        $('#display').append(state);
    });
    

    You can also add in $('#display').empty(); to clear the current data inside of the #display element before adding in the new data.

    Here is the code that you could edit to load in a page with the text that you would like on it

    $('.state').on('click', function(){
        var state = $(this).val();
        $.ajax({
            type: "POST",
            url: 'goes here',
            data: {state : state},
            success: function(displayState){
                $('#display').html(displayState);
            }
        )};
    });
    

    The page that you load in could then be written to display info depending on which state you clicked.