我一直試圖使用ajax從php調用saveTaskDB
函數。它將作爲成功返回,但數據庫不會更新。我試過創建一個'create.php'
,其中只有saveTaskDB
函數代碼,當我直接調用這個文件時,它會成功返回,並且會更新我的數據庫。我不知道爲什麼我不能在我的php中調用特定的函數,我也想知道如何將我的php函數存儲到單個php文件中並通過AJAX調用它們。感謝任何能夠幫助我的人。使用ajax無法調用特定的php函數
我有我的代碼是這樣
tasklogger.js:
function saveTask(){
$.ajax({
method: "POST",
url:"../_tasklogger/classes/tasklog.php", //the page containing php script
data:{ action: 'add',
date: $("#date").val(),
taskName: $("#taskName").val(),
taskType: $("#taskType").val(),
duration: $("#duration").val(),
startTime: $("#startTime").val(),
endTime: $("#endTime").val()
},
success: function(data){
goSuccess();
}
});
}
tasklog.php
require_once 'dbconfig.php';
if (isset($_POST['action']) && !empty($_POST['action'])){
$date= $_POST['date'];
$taskName= $_POST['taskName'];
$taskType= $_POST['taskType'];
$duration= $_POST['duration'];
$startTime= $_POST['startTime'];
$endTime= $_POST['endTime'];
saveTaskDB($date, $taskName, $taskType, $duration, $startTime, $endTime);
}
function saveTaskDB($date, $taskName, $taskType, $duration, $startTime, $endTime){
try{
$stmt = $db_con->prepare("INSERT INTO tasks (TaskDate,TaskName,TaskType,Duration,StartTime,EndTime) VALUES(:tdate, :tname, :ttype, :dur, :stime, :etime)");
$stmt->bindParam(":tdate", $date);
$stmt->bindParam(":tname", $taskName);
$stmt->bindParam(":ttype", $taskType);
$stmt->bindParam(":dur", $duration);
$stmt->bindParam(":stime", $startTime);
$stmt->bindParam(":etime", $endTime);
if($stmt->execute()){
echo 'alert("success")';
}else{
echo 'alert("wrong")';
}
}
catch(PDOException $e){
echo $e->getMessage();
}
}
create.php
require 'dbconfig.php';
$date= $_POST['date'];
$taskName= $_POST['taskName'];
$taskType= $_POST['taskType'];
$duration= $_POST['duration'];
$startTime= $_POST['startTime'];
$endTime= $_POST['endTime'];
try{
$stmt = $db_con->prepare("INSERT INTO tasks (TaskDate,TaskName,TaskType,Duration,StartTime,EndTime) VALUES(:tdate, :tname, :ttype, :dur, :stime, :etime)");
$stmt->bindParam(":tdate", $date);
$stmt->bindParam(":tname", $taskName);
$stmt->bindParam(":ttype", $taskType);
$stmt->bindParam(":dur", $duration);
$stmt->bindParam(":stime", $startTime);
$stmt->bindParam(":etime", $endTime);
if($stmt->execute()){
return true;
}else{
return false;
}
}
catch(PDOException $e){
echo $e->getMessage();
}
在'taskLogger.js'什麼是你把'dateType的期望:「dataString''在POST? –
什麼是'dateType:'dataString','? –
我對php和ajax還很陌生。我嘗試使用'dataType:json'作爲數據類型並傳入一個有效的json,但它不會更新我的數據庫。當我在線閱讀論壇時,我遇到了'dataType:dataString',神奇的是,我的查詢直接調用'create.php',但沒有tasklog.php –