How to put JQuery/Ajax inside shortcode?

The purpose of this plugin is to create a list that users can modify with up or down votes. The shortcode is supposed to display the list on a page and use JQuery to fadeIn and fadeOut while updating the database.

A demo of the concept is available at http://bucketlingerwedding.com/80s-music-reception/ (note: the working code does not yet use AJAX).

Read More

I would like to put this plugin in the WordPress Repository, but the AJAX is killing me. The following is the latest code. It shows only a page with a blank content area. I need to get this code to update the database with AJAX, and to avoid re-loading the page, so that I can work in animations/transitions.

The code is commented to reflect my understanding of what I’m trying to do.

Code:

/*
*
*
SHORTCODE
*
*
*/

add_shortcode('list-up-down', 'cb_lud_scfunc');

//This creates the shortcode.
function cb_lud_scfunc() {
//Define some basic variables.
global $wpdb;
$cb_lud_prefix = $wpdb->prefix;
$cb_lud_table = $cb_lud_prefix . 'cb_list_up_down';
$cb_lud_homeurl = home_url();
$cb_lud_upimg = plugins_url('list-up-down/images/up-arrow.png', _FILE_);
$cb_lud_downimg = plugins_url('list-up-down/images/down-arrow.png', _FILE_);
$cb_lud_sample_query = $wpdb->query('SELECT * FROM '.$cb_lud_table);
$cb_lud_field1_name = $wpdb->get_col_info('name',1);
$cb_lud_field2_name = $wpdb->get_col_info('name',2);

/*
CREATE THE JAVASCRIPT/JQUERY FUNCTION
*/
//Create the Javascript and AJAX
//add_action('init', 'cb_lud_action_javascript');

function cb_lud_action_javascript() {
?>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'></script>
 <script type='text/javascript' >

$(document).ready(function(){
//JQuery for the submission of a new list item.
    $('input').click(function(e){
        e.preventDefault(); //put e in function.
        var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';

        if ($(this).hasClass('up-arrow')) {
            var arrowdirection = 'up';
            var entry = $(this).val();
        }
        else if ($(this).hasClass('down-arrow')) {
            var arrowdirection = 'down';
            var entry = $(this).val();
        }

        var data = {
            action: 'cb_lud_arrow_action',
            arrow: arrowdirection,
            entryID: entry
        };

        $.ajax ({
            type: 'POST',
            url: ajaxurl,
            data: data,
            success: function(){
                $('.line-items-rows').fadeOut('fast').delay(1000).fadeIn('fast');
            }
        });

        /*var data = {
            action: 'cb_lud_up_arrow_action',
            arrow-direction: 'up',
            entry-id: arrow-entry-id
        };

    $.ajax ({
        type: 'POST',
        url: ajaxurl,
        data: data,
        success: function(){

//$('#cb_lud_list').fadeOut('fast').delay(1000).$('#cb_lud_list').fadeIn('fast');
            $alert('it worked');
        }
    });*/
});
});

</script>
<?php
//End Javascript function.  
}

//Call the javascript function.
//Rather than hook into an action, call whenever shortcode is in a page.
cb_lud_action_javascript();

/*
*
CREATE THE AJAX (HELP!)
*
*/

/*
ARROW CALLBACK
*/

//Use the WordPress AJAX functions
//Apparently, there has to be an if->then statement depending on whether the user is an admin.
if( is_admin() )
{
add_action('wp_ajax_cb_lud_arrow_action', 'cb_lud_arrow_callback');
add_action('wp_ajax_nopriv_cb_lud_arrow_action', 'cb_lud_arrow_callback');
}
else
{
//Assume the 'else' is the normal execution of the shortcode.
     //Want to get the POST values from the form, above.
     //These don't seem to be working.

    $cb_lud_entry_id = $_POST['entry'];
    $cb_lud_arrow_direction = $_POST['arrowdirection'];

     //If the post value is 'up', do this. If 'down', do this.      
    if ($cb_lud_arrow_direction == 'up') {
        $wpdb->query('UPDATE '.$cb_lud_table.' SET up_votes=up_votes+1
        WHERE entry_ID='.$cb_lud_entry_id.'');
    }

    else if ($cb_lud_arrow_direction == 'down') {
        $wpdb->query('UPDATE '.$cb_lud_table.' SET down_votes=down_votes+1
        WHERE entry_ID='.$cb_lud_entry_id.'');
    }

die(); // this is required to return a proper result
}


//Create the function that executes the AJAX Callback
function cb_lud_arrow_callback(){
    }

/*
CREATE THE FORM
*/
//Create the form to allow users to add records
    $cb_lud_sc_form = '
        <form id="list-up-down-form" name="list-up-down-form" action="" method="post">
        <table border="0">
            <tr>
//Using inputs rather than links because inputs can contain values.
                <td><h2>'.$cb_lud_field1_name.':</h2><input id="field1_input" name="field1_input" type="text"></input></td>
                <td><h2>'.$cb_lud_field2_name.':</h2><input id="field2_input" name="field2_input" type="text"></input></td>
                <td valign="bottom"><input name="add_record" type="submit" value="Add Record" /></td>
            </tr>
        </table>
        </form>
        ';

/*
DEFINE HOW THE FORM HANDLES THE INPUT(S)
*/
$field1_data = htmlspecialchars($_POST['field1_input'], ENT_QUOTES);
$field2_data = htmlspecialchars($_POST['field2_input'], ENT_QUOTES);
$up_votes = 0;
$down_votes = 0;
$new_data = array(
    $cb_lud_field1_name => $field1_data,
    $cb_lud_field2_name => $field2_data,
    'up_votes' => $up_votes,
    'down_votes' => $down_votes,
    );
$format = array('%s', '%s', '%f', '%f');

if (isset($field1_data) && !empty($field1_data) && isset($field2_data) &&!empty($field2_data)) {
    $wpdb->insert(
        $cb_lud_table, $new_data, $format
    );
}

/*
DISPLAY THE LIST
*/          
//Get the list from the database, and set the variables for display in the output.
$get_list = $wpdb->get_results('SELECT entry_ID, '.$cb_lud_field1_name.' AS "field1", '.$cb_lud_field2_name.' AS "field2", up_votes, down_votes, up_votes - down_votes AS "total_votes"
    FROM '.$cb_lud_table.'
    GROUP BY entry_ID
    ORDER BY total_votes DESC
    ',OBJECT);

//Check if list is null, and if so, set a variable to display a warning. Otherwise, display the list.
if (empty($get_list)) {
    $cb_lud_sc_output .= "<em>Warning: You don't seem to have any records for this list. Why don't you add some now?</em>";
    $cb_lud_sc_output .= $cb_lud_sc_form;
    return $cb_lud_sc_output;
}
else {
    $cb_lud_sc_output .= $cb_lud_sc_form;
    $cb_lud_sc_output .= '</br>';
    $cb_lud_sc_output .= '<table id="cb_lud_list" border="1" cellpadding="10">';
    $cb_lud_sc_output .= '<tr><td align="center"><strong><a id="sort-by-field1" href="">'.$cb_lud_field1_name.'<a></strong></td><td align="center"><strong>'.$cb_lud_field2_name.'</strong></td><td align="center"><strong>Score</strong></td><td align="center"><strong>Vote Up/Down</strong></td></tr>';
        foreach ($get_list as $list_items) {
            $cb_lud_sc_output .= '<tr class="line-items-rows"><td>'.stripslashes($list_items->field1).'</td><td>'.stripslashes($list_items->field2).'</td><td>'.$list_items->total_votes.'</td><td><form id="up-down-arrows-form" action="" method="post"><input class="up-arrow" name="arrow-up-ID-'.$list_items->entry_ID.'" type="image" src="'.$cb_lud_upimg.'" value="'.$list_items->entry_ID.'"/>&nbsp;<input class="down-arrow" name="arrow-down-ID-'.$list_items->entry_ID.'" type="image" src="'.$cb_lud_downimg.'" value="'.$list_items->entry_ID.'"/></form></td></tr>';
            }
    $cb_lud_sc_output .= '</table>';
    return $cb_lud_sc_output;
}
};
/*
END SHORTCODE
*/

Related posts

Leave a Reply

2 comments

  1. You should probably write a plugin, which has the shortcode function. You can separate the AJAX/jQuery code in a plugin, but not in a shortcode.

  2. ave you tried to put it in the Shortcode-function?
    I would suggest this:

    function my_shortcode() {
    
    ?>
      <script>
        alert('test')
      </script>
    <?php
    
    }
    add_shortcode( 'my_shortcode', 'my_shortcode');