我从$ sql获取了一个未定义的用户名,该用户名应该是查询返回的数据。
$('#userlist').on('change', function () {
var selected = $("select option:selected").text();
console.log(selected);
// use ajax to run the check
$.ajax({
url: '/php/connect/userdropdowncheck.php',
type: 'JSON',
data: selected,
success: formfill,
error: function (xhr, status, err) { console.log(xhr, status, err); }
});
function formfill(sql) {
var username = sql['UserLogin'];
var email = sql['UserEmail'];
var admin = sql['admin'];
var firstname = sql['firstname'];
var lastname = sql['lastname'];
var title = sql['title'];
var company = sql['company'];
console.log(username);
if (username.length > 0) {
console.log('Found user');
console.log(username);
$('#username').html($username);
}
else {
console.log('Failed to find user');
}
}
});
PHP代码:
<?php
session_start();
include 'anonconnect.php';
// username and password sent from form
$myusername= $_POST['selected'];
$sql = $dbh->prepare("SELECT * FROM Users WHERE UserLogin= :login");
$sql->execute(array(':login' => $myusername));
$user = $sql->fetch();
/*** close the database connection ***/
$dbh = null;
if($user->rowCount() == 1){
echo 1;
echo json_decode($user);
else {
echo 0;
}
?>
它正在从选定的下拉列表中拉出文本然后传递它,但返回的函数找不到它。
答案 0 :(得分:1)
你的jquery代码可能是:
function formfill(sql) {
var username = sql['UserLogin'];
var email = sql['UserEmail'];
var admin = sql['admin'];
var firstname = sql['firstname'];
var lastname = sql['lastname'];
var title = sql['title'];
var company = sql['company'];
console.log(username);
if (username.length > 0) {
console.log('Found user');
console.log(username);
$('#username').html($username);
}
else {
console.log('Failed to find user');
}
}
$('#userlist').on('change', function () {
var selected = $("select option:selected").text();
$.ajax({
url: '/php/connect/userdropdowncheck.php',
type: 'POST',
data: {UserLogin:selected},
success: function(data){
formfill(data)
},
error: function (xhr, status, err) { console.log(xhr, status, err); }
});
});
和你的php代码:
<?php
session_start();
include 'anonconnect.php';
// username and password sent from form
$myusername= $_POST['UserLogin'];
$sql = $dbh->prepare("SELECT * FROM Users WHERE UserLogin= :login");
$sql->execute(array(':login' => $myusername));
$user = $sql->fetch();
/*** close the database connection ***/
$dbh = null;
if($sql->rowCount() == 1){
//echo 1; //if you echo this it will cause that your jquery code will not be able to read the response as JSON and serialize it in array
echo json_encode($user); // php array to json object
} else {
echo 0;
}
?>
答案 1 :(得分:0)
如果您使用 JSON 类型,则可以序列化您的javascript数组,然后传递给php。
例如:var jsonString = JSON.stringify(Array);
在php中,使用json_decode()
和json_encode()
例如:$data = json_encode($sql)