使用参数从JavaScript调用PHP脚本

时间:2018-02-15 17:49:27

标签: javascript php jquery ajax

我已经对Google和StackOverflow进行了大量研究,但我无法解决这个问题(这就是为什么这个问题没有重复): 我有一个js函数,在点击(工作)时调用。有了这个功能,我试着调用一个PHP脚本来执行......但它没有做出反应......请告诉我错误的原因(完整的解决方案将不胜感激......)< / p>

PHP代码:

<?php
$servername = "bot-sam.lima-db.de:3306";
$username = "USER379138";
$password = "pwd";
$dbname = "db_379138_1";

$q = $_POST['q'];
$a = $_POST['a'];

function alert($msg) {
    echo "<script type='text/javascript'>alert('$msg');</script>";
}

echo $q . $a;
// echo and alert are not opening so i think the php script isn't executing
alert("question is " . $q);
alert("answer is " . $a);

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$sql = "INSERT INTO knowledge_base ('question', 'answer')
VALUES ($q, $a)";

if (mysqli_query($conn, $sql)) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>

JavaScript函数(被正确调用; jQuery正常工作):

function myfunc() {
    var question = "test1";
    var answer = "test2";
    $.ajax({
        url: 'phpscript.php',
        type: 'POST',
        data: {q: question, a: answer},
        dataType: 'json',
        sucess: console.log("SQL entry made")
    });
}

我很抱歉提出这么简单的问题,但我无法解决问题......

1 个答案:

答案 0 :(得分:1)

尝试使用以下代码

function myfunc() {
    var question = "test1";
    var answer = "test2";
    $.ajax({
        url: 'phpscript.php',
        type: 'POST',
        data: {q: question, a: answer},
        dataType: 'json',
        success: function(result) {
         console.log(result);
       }
    });
}