需要通过ajax插入数据单击按钮

时间:2018-10-09 00:33:32

标签: php ajax wordpress

我需要单击按钮,才能在wordpress中用ajax插入数据库。如果可以的话,请帮我。我不知道怎么了

// Script.js

function action() {
    $.ajax({
        type: 'POST',
        url: 'process.php',
        data: {------------------->What's going on there?               
        }, 
        success: function (data) {
            $("#result").html(response);
        },
        error: function (data) {
            $("#result").html("Error");
        }
    });
}
<input type="submit" name="" value="rating" id="button" onclick = "action();">

<div id="result"></div>

<!-- process.php -->
<?php
    global $wpdb;
               
    $wpdb->insert('rating', array( 
        'rating_postid'=>'5', 
        'rating_posttitle'=>'title'
        )
    ); 
?>

2 个答案:

答案 0 :(得分:0)

尝试以下代码:

HTML代码:

<input type="submit" name="" value="rating" id="button" onclick = "action();">

<div id="result"></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function action() {
    $.ajax({
        type: 'POST',
        url: 'process.php',
        data: {
            id: 1
        },
        success: function (data) {
            $("#result").html(response);
        },
        error: function (data) {
            $("#result").html("Error");
        }
    });
}
</script>

您的PHP文件还可以。.

答案 1 :(得分:-1)

HTML文件

<input type="submit" name="" value="rating" id="but">
<div id="result"></div>

JavaScript文件

but=document.getElementById('but');
but.addEventListener('click', function (){
    $.ajax({
        type: 'POST',
        url: 'process.php',
        data: {
            id: 1
        }, ??
        success: function (data) {
            $("#result").html(response);
        },
        error: function (data) {
            $("#result").html("Error");
        }
    });
});

php文件process.php

<?php
    $conn=mysqli_query('localhost','root','','DB');
    $query=' Insert Query '; 
    $fireResult=mysqli_query($conn,$query);
    //json output
    json_encode($fireResult); 
?>