我创建了一个Wordpress网站,里面有乐队的演唱会。所有登录的用户都可以选择是否参加过该特定的演出。类似于集合列表。fm。
所以我创建了一个新表wp_gigs_attending. 此表有3个字段:
参加id当然是主键(A.I),参加id是您参加的演出的id,用户id是您的用户id,所以是当前用户的id。
一切正常,但我在模板中添加了PHP代码,也没有ajax。当我点击表单时,页面会刷新,这看起来不是很好。
所以我想用ajax提交表单(只有一个按钮)。
在single-gig.php 模板:
<?php if ( is_user_logged_in() ) {  ?>
    <div class="attended">
        <form method="post" id="attending" class="attended__form">
            <input type="submit" name="submit" value="attend" />
        </form>
    </div>
<?php } ?>
<script>
    jQuery(function(){
        jQuery(\'#attending\').on(\'submit\', function(e){
            e.preventDefault();
            jQuery.ajax({
                type: \'post\',
                url: \'<?php bloginfo(\'template_directory\'); ?>/inc/attend.php\',
                data: jQuery(\'#attending\').serialize(),
                succes: function(){
                    alert(\'form was succesfully submitted\');
                }
            })
        });
    });
</script>
 在我的/inc文件夹中,我必须编写代码,检查我是否参加过那场演出。
如果我没有参加过那场演出->单击表单按钮->在表格中插入行如果我参加过那场演出->单击表单按钮->删除那行这是中的代码attended-gig.php:
//get the user id
$current_user = wp_get_current_user();
$current_user_id = $current_user->ID;
//get the post id
$current_post_id = get_the_ID();
//check if already attended
$attending = $wpdb->get_var(
    $wpdb->prepare(
        "SELECT attending_id FROM " . $wpdb->prefix . "gigs_attending
        WHERE user_id = %d AND post_id = %d LIMIT 1",
        $current_user_id, $current_post_id
    )
);
if ( $attending > 0 ) {
    $isAttending = true;
} else {
    $isAttending = false;
}
//actions
if($isAttending == false) {
    //if not attended yet, insert the user_id and post_id in the table
    $success = $wpdb->insert("wp_gigs_attending", array(
        "user_id" => $current_user_id,
        "post_id" => $current_post_id,
    ));
} else {
    //if attended yet, delete the row in the table
    $succes = $wpdb->get_var(
        $wpdb->prepare(
            "DELETE FROM " . $wpdb->prefix . "gigs_attending
            WHERE user_id = %d AND post_id = %d LIMIT 1",
            $current_user_id, $current_post_id
        )
    );
}
 我知道这些查询工作正常。但我在该文件上收到一个500(内部服务器错误)。
想要的结果:
用户尚未参加该特定的演出->单击按钮->在表中插入新行->该按钮现在有一个额外的类,因此可以看到他参加了该演出用户可能犯了一个错误,选择参加某个特定的演出。他单击同一个按钮撤消它->删除表中的那一行->删除按钮上的额外类当用户去参加演唱会时。php,必须看到他已经参加了那场演出,所以attended 班级必须按那个按钮。