weixin_33676492 2020-01-20 17:45 采纳率: 0%
浏览 86

AJAX Wordpress插入

I have a complete/completed button on a custom post type page.

And It works, When someone clicks the button it sends the right data to the db and adds marks it complete but I want to conver this to ajax but the button itself doesn't send any data. I send the post type and the user id to the server based on the post they are on. And I am trying to figure this out.

In single.php

<form action='' method="post" class='comp-btn'>
   <input class='workout-submit' id="workout-submit"type='submit' name='complete' value='Complete'/>
 </form>

This is the post req

//Inserts row into database
if (isset($_POST['complete'])):
$wpdb->insert('wp_completed_workouts',
    array(
      userID => $current_userID,
      postID => $current_postID,
        )
    );
    endif;

TLDR: I have this post request (that works)I would like to turn into an AJAX call. Cause I don't want it to reload every time someone hits the complete button.

  • 写回答

1条回答 默认 最新

  • weixin_33705053 2020-01-21 05:50
    关注

    Since you are using Wordpress, AJAX works best in sending data to functions.php.

    First, in your html/js file:

    $('.comp-btn').on('submit', function(){
        $.ajax({
            type: 'POST',
            url: "../../../../wp-admin/admin-ajax.php",
            data: {'action':'sendworkout','complete':$('.workout-submit').val()},
            success: function(response){
                console.log(response); // shows 'success'
                // do things here
            }
        });
    });
    

    Second, in your WP functions.php

    add_action('wp_ajax_sendworkout', 'sendworkout');
    add_action('wp_ajax_nopriv_sendworkout', 'sendworkout');
    function sendworkout(){
        $workoutcomplete = $_POST['complete'];
        if($workoutcomplete){
            //DB insert here
        }
        wp_send_json_success('success');
    }
    

    Note that the 'action' in ajax syntax is referring to the function name in your functions.php, and the 'complete' refers to the $_POST['complete'] in your functions.php

    评论

报告相同问题?

悬赏问题

  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64