如何通过前端页面调用插件功能提交wordpress

时间:2018-02-20 11:15:30

标签: wordpress forms function plugins

我在插件中有一个函数,可以在数据库中插入值,我希望在前端页面上提交表单时调用此函数。我该怎么办? 我不知道该怎么做 这是我现在要打电话的功能我不知道还能做什么

function jal_install_data() {
    global $wpdb;

    $welcome_name = 'Mr. WordPress';
    $welcome_text = 'Congratulations, you just completed the installation!';

    $table_name = $wpdb->prefix . 'dbquestions';

    $wpdb->insert( 
        $table_name, 
        array( 
            'time' => current_time( 'mysql' ), 
            'name' => $welcome_name, 
            'text' => $welcome_text, 
        ) 
    );
}

我没有在前端使用表单,而是使用div类,类名是问题 这是我要调用该功能的按钮

<input type="button" id='next' value="Next" onlick="sum_values()">

2 个答案:

答案 0 :(得分:0)

Please try JSON.stringify() data before sending it to the AJAX as below:
function sum_values() {

var data = JSON.stringify({ 
    action: 'savedata', 
    'moneyOf': document.getElementById('priceSlider').value,
    'emailOf': document.getElementById('inputheaderBox').value
});

jQuery.ajax({
        type: 'POST',
        url: "<?php echo admin_url('admin-ajax.php'); ?>",
        data: data,               
        success: function(data){
            //alert('success');
            console.log(data);
        },
        error: function(errorThrown){
            console.log(errorThrown);
        }
    });
}

and write following code in functions.php file to save data into database:

<?php
  function savedata(){

global $wpdb;
$wpdb->insert(
    'table_name',
    array(
        'field1' => $_POST['moneyOf'],
        'field2' => $_POST['emailOf'],
    ),
    array(
        '%s',
        '%s'
    )
);

die();
return true;
}
//
add_action('wp_ajax_savedata', 'savedata'); 
add_action('wp_ajax_nopriv_savedata', 'savedata'); 
?>

答案 1 :(得分:0)

上面的代码需要进行一些修改才能调用该函数,而且它确实是修改后的版本

function abc(){


jQuery.ajax({
        type: 'POST',
        url: "<?php echo admin_url('admin-ajax.php'); ?>",
        data: { action: 'savedata', 'question_id': document.getElementById('question_id').value, 'text': document.getElementById('text').value },               
        success: function(data){
            alert('success');
            console.log(data);
        },
        error: function(errorThrown){
            console.log(errorThrown);
        }
    });
}

这是php函数

function savedata(){
echo "<pre>";print_r($_POST);exit;
global $wpdb;
$wpdb->insert('questoptions',
     array(
        'question_id' => $_POST['question_id'],
        'text' => $_POST['text']

),
    array(
        '%s',
        '%s'
    )
);

die();
return true;
}

它正在调用该函数,但问题是数据库表仍为空