[英]Call PHP Script from JavaScript with parameters
I have done a lot of research on Google and StackOverflow but I can't solve this problem (that's why this question is no duplicate): I have a js function, which is called on click (working). 我已经在Google和StackOverflow上进行了大量研究,但无法解决此问题(这就是为什么这个问题没有重复的原因):我有一个js函数,该函数在单击(工作)时被调用。 With this function I'm trying to call a PHP script to execute... But it doesn't react... Please tell me what's wrong (complete solution would be appreciated...)
使用此功能,我试图调用PHP脚本来执行...但是它没有反应...请告诉我出了什么问题(完整的解决方案将不胜感激...)
PHP code: 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 function (which gets called properly; jQuery working): 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")
});
}
I'm sorry to ask such a simple question but I just can't solve the problem... 很抱歉提出这样一个简单的问题,但我无法解决问题...
Try to use the below code 尝试使用以下代码
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);
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.