想要使用JQuery,Ajax和PHP将数据插入MySql

时间:2022-09-25 16:08:57

I want to insert data into mysql using JQuery, Ajax and PHP. I made function for it but it is not working. Can anyone help? This is my Ajax function.

我想使用JQuery,Ajax和PHP将数据插入到mysql中。我为它做了功能,但它不起作用。有人可以帮忙吗?这是我的Ajax功能。

function insertComment(textboxID, event, questionID) {
    var comment = $(textboxID).val();
    ajaxCall(questionID, comment);
}



    function ajaxCall(questionID, comment){
    $.ajax({
        type:"POST",
        url:"insertComment.php",
        data:{Q_ID:questionID, comment:comment},
        success: function(data){
            alert('data Added in MySql');
        }
    });
}

and this is my insertComment.php code for inserting data

这是我插入数据的insertComment.php代码

<?php
$servername = "localhost";
$user = "root";
$pass = "";
$db = "comments";

$conn = mysqli_connect($servername, $user, $pass, $db);

if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
$Q_ID = $_POST['Q_ID'];
$comment = $_POST['comment'];
$sql = "INSERT INTO comments(Q_ID, C_Description) VALUES('$Q_ID','$comment')";
mysqli_query($conn, $sql);
mysqli_close($conn);
echo "done";
?>

but it's not working. Can you point out what mistake I am doing in code.

但它不起作用。你能指出我在代码中犯的错误吗?

1 个解决方案

#1


0  

If you are sure that ajaxCall is being called well, Why don't you try the following alternative, although there isn't much difference.

如果您确定ajaxCall被正确调用,为什么不尝试以下替代方案,尽管没有太大区别。

function ajaxCall(questionID, comment){
    $.post("insertComment.php", {Q_ID: questionID, comment: comment}, function(data, status){
        alert("Data: " + data + "\nStatus: " + status);
    });
}

#1


0  

If you are sure that ajaxCall is being called well, Why don't you try the following alternative, although there isn't much difference.

如果您确定ajaxCall被正确调用,为什么不尝试以下替代方案,尽管没有太大区别。

function ajaxCall(questionID, comment){
    $.post("insertComment.php", {Q_ID: questionID, comment: comment}, function(data, status){
        alert("Data: " + data + "\nStatus: " + status);
    });
}