dongpu1879 2012-06-03 17:02
浏览 52
已采纳

在Wordpress插件中将AJAX发布到回调函数

Pulling my hair out with AJAX once again. This is a simple list plugin that I am working on. I'm trying to add JQUERY to the shortcode, with an AJAX callback.

The most interesting part of this is that the Javascript/JQuery is not making it onto the page. For instance, an alert box is supposed to come up when the shortcode is called on the page (so that I know it is working), and it is supposed to say "at least this is working." It should happen as soon as the document is ready. But for some reason, there's no alert box, leading me to believe that I'm never getting to the AJAX callback, because the original JQuery code, which specifies the AJAX callback, is broken somehow.

You can see this at around line 34, below. If I can figure out why the javascript is not working, I bet the rest will fall in line. I've tried putting the JQuery in a variable and returning it, echoing it, etc. Have also tried putting the JQuery code before and after the form in the code. Still doesn't work.

Here's the code:

/*
*
*
SHORTCODE
*
*
*/

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

function cb_lud_scfunc() {
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
*/
//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(){
alert('at least this is working');
//JQuery for the submission of a new list item.
$('#list-up-down-form').submit(function(e){
    e.preventDefault(); //Works to prevent normal submission of the form.

    var field1_input = $('#field1_input').val();
    var field2_input = $('#field2_input').val();

    var data = {
        action: 'cb_lud_ajax_action',
        field1: field1_input,
        field2: field2_input,
        };

    $.ajax ({
        type: 'POST',
        url: ajaxurl,
        data: data,
        success: function() {
            alert('It worked!');
            }
        });
});
});
</script>
<?php
//End Javascript function.  
}

/*
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>
                <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>
        ';

/*
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 border="1" cellpadding="10">';
    $cb_lud_sc_output .= '<tr><td align="center"><strong>'.$cb_lud_field1_name.'</strong></td><td align="center"><strong>'.$cb_lud_field2_name.'</strong></td><td align="center"><strong>Score</strong></td></tr>';
        foreach ($get_list as $list_items) {
            $cb_lud_sc_output .= '<tr><td>'.$list_items->field1.'</td><td>'.$list_items->field2.'</td><td>'.$list_items->total_votes.'</td></tr>';
        }
    $cb_lud_sc_output .= '</table>';
    return $cb_lud_sc_output;
}
return $cb_lud_sc_output;   

/*
CREATE THE AJAX
*/

//Use the Wordpress AJAX functions
add_action('wp_ajax_cb_lud_ajax_action', 'cb_lud_ajax_callback');
add_action('wp_ajax_nopriv_cb_lud_ajax_action', 'cb_lud_ajax_callback');

//Create the function that executes the AJAX Callback
function cb_lud_ajax_callback() {
global $wpdb;
$prefix = $wpdb->prefix;
$cb_lud_table = $prefix . 'cb_list_up_down';


        $field1_data = $_POST['field1'];
        $field2_data = $_POST['field2'];
        $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');

        /*$wpdb->insert(
            $cb_lud_table, $new_data, $format
        );*/

        $wpdb->query('INSERT INTO
            '.$cb_lud_table.' ('.$cb_lud_field1_name.', '.$cb_lud_field2_name.', up_votes, down_votes)
            VALUES ('.$field1_data.', '.$field2_data.', '.$up_votes.', '.$down_votes.')
        ');
die(); // this is required to return a proper result
}
};
/*
END SHORTCODE
*/
  • 写回答

1条回答 默认 最新

  • dongxin2734 2012-06-03 22:47
    关注

    After re-thinking the shortcode, there was no reason to include an AJAX call for this portion of the code. It was easier just to have the form insert data to the database on submit, and use an "if" statement to control whether the form was actually filled out properly.

    The code below, comments out all the AJAX and callbacks, and works perfectly.

    Also, I figured out a way to debug the javascript/jquery. Rather than having it called by another function, I defined the function, and called it directly, which worked.

    The Working Code (Hooray!):

    /*
    *
    *
    SHORTCODE
    *
    *
    */
    
    add_shortcode('list-up-down', 'cb_lud_scfunc');
    
    function cb_lud_scfunc() {
    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
    */
    //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(){
    alert('at least this is working');
    //JQuery for the submission of a new list item.
    $('#list-up-down-form').submit(function(e){
        e.preventDefault(); //Works to prevent normal submission of the form.
    
        var field1_input = $('#field1_input').val();
        var field2_input = $('#field2_input').val();
    
        var data = {
            action: 'cb_lud_ajax_action',
            field1: field1_input,
            field2: field2_input,
            };
    
        $.ajax ({
            type: 'POST',
            url: ajaxurl,
            data: data,
            success: function() {
                alert('It worked!');
                }
            });
    });
     });
    </script>
    <?php
    //End Javascript function.  
    }
    
    //Call the javascript function
    cb_lud_action_javascript();
    */
    
    /*
    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>
                    <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
        );
    }
    else {
    }
    /*$wpdb->query('INSERT INTO
        '.$cb_lud_table.' ('.$cb_lud_field1_name.', '.$cb_lud_field2_name.', up_votes, down_votes)
        VALUES ('.$field1_data.', '.$field2_data.', '.$up_votes.', '.$down_votes.')
    ');*/
    
    /*
    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 border="1" cellpadding="10">';
        $cb_lud_sc_output .= '<tr><td align="center"><strong>'.$cb_lud_field1_name.'</strong></td><td align="center"><strong>'.$cb_lud_field2_name.'</strong></td><td align="center"><strong>Score</strong></td></tr>';
            foreach ($get_list as $list_items) {
                $cb_lud_sc_output .= '<tr><td>'.stripslashes($list_items->field1).'</td><td>'.stripslashes($list_items->field2).'</td><td>'.$list_items->total_votes.'</td></tr>';
            }
        $cb_lud_sc_output .= '</table>';
        return $cb_lud_sc_output;
    }
    return $cb_lud_sc_output;   
    
    /*
    CREATE THE AJAX
    */
    
    /*
    //Use the Wordpress AJAX functions
    add_action('wp_ajax_cb_lud_ajax_action', 'cb_lud_ajax_callback');
    add_action('wp_ajax_nopriv_cb_lud_ajax_action', 'cb_lud_ajax_callback');
    */
    
    //Create the function that executes the AJAX Callback
    /*
    function cb_lud_ajax_callback() {
    global $wpdb;
    $prefix = $wpdb->prefix;
    $cb_lud_table = $prefix . 'cb_list_up_down';
    
            $field1_data = $_POST['field1'];
            $field2_data = $_POST['field2'];
            $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');
    
            $wpdb->insert(
                $cb_lud_table, $new_data, $format
            );
    
            $wpdb->query('INSERT INTO
                '.$cb_lud_table.' ('.$cb_lud_field1_name.', '.$cb_lud_field2_name.', up_votes, down_votes)
                VALUES ('.$field1_data.', '.$field2_data.', '.$up_votes.', '.$down_votes.')
            ');
    die(); // this is required to return a proper result
    }
    */
    };
    
    /*
    END SHORTCODE
    */
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 QT6颜色选择对话框显示不完整
  • ¥20 能提供一下思路或者代码吗
  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下