[英]Ajax call PHP function
I want to call a php file from js. 我想从js调用php文件。 I do not have experience with ajax so i don't really know how to use it properly. 我没有使用Ajax的经验,所以我真的不知道如何正确使用它。 I use this function : 我使用这个功能:
function start(cod){
var result =0;
$.ajax({
type: "POST",
url: "CheckDetails.php",
datatype: "html",
async: false,
data: {cod: cod},
success: function(data) {
result = data;
}
});
return result;
}
And the PHP file : 和PHP文件:
<?php
check($_POST['cod']);
function check($cod)
{
mysqli_report(MYSQLI_REPORT_STRICT);
$dbhandle = 0;
try {
$username = 'root';
$password = '';
$hostname = 'localhost';
$dbhandle = new mysqli($hostname, $username, $password, 'db') ;
} catch (Exception $e ) {
echo "Service unavailable";
exit;
}
$name = '';
$date = '';
$hour = '';
$result = 0;
$codeResult = mysqli_query($dbhandle, "SELECT name, date, hour FROM records WHERE cod = '$cod'");
if (!$codeResult) {
echo('Database error: ' . mysqli_error($dbhandle));
} else
if ($row = mysqli_fetch_assoc($codeResult)) {
$name = $row{"name"};
$date = $row{"date"};
$hour = $row{"hour"};
$result = 1;
}
echo $result;
}
?>
But it seems it doesnt work. 但似乎不起作用。 I dont really know where is the problem. 我真的不知道问题出在哪里。
it seems in your DB-query you only read the first result set from your table, and you don't return the results. 似乎在数据库查询中,您仅从表中读取了第一个结果集,而没有返回结果。 If I get your intentions right you would have in your last 'else' clause something like: 如果我的意图正确,那么您在最后一个“ else”子句中将包含以下内容:
...
else {
while($row = mysqli_fetch_array($codeResult)) {
$data[] = array("name" => $row["name"], "date" => $row["date"], "hour" => $row["hour"]);
}
}
...
with having $data declared as array earlier in the code. 在代码前面将$ data声明为数组。 This way you would have your query results stored in a $data array which you could return as it is or as a json_encoded object. 这样,您会将查询结果存储在$ data数组中,可以按原样或以json_encoded对象的形式返回。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.