从$ .ajax调用中检索参数的问题 [英] Issue with retrieving a parameter from a $.ajax call
问题描述
我有以下$ .ajax电话:
Hey guys I have the following $.ajax call:
$.ajax({
type: "POST",
dataType: "json",
url: '/pcg/popups/getNotes.php',
data:
{
'nameNotes': notes_name.text(),
},
success: function(response) {
$('#notes_body').text(response.the_notes);
alert(response.the_notes);
}
)};
现在专注于data:
,可以说我发送了"BillCosby".那将被发送到指定的文件,我在该文件中有这个文件:
Now focus on the data:
lets say I sent 'BillCosby'. That will be sent over to the file specified and i have this inside that file:
$username_notes = $_POST['nameNotes'];
现在让我说我将像这样在json中返回$ username_notes ...
Now lets say I was to just have $username_notes return in the json like this...
$returnArray = array( 'the_notes' => $username_notes );
echo json_encode($returnArray);
这将起作用,响应将是BillCosby.现在,当我尝试使用PDO从我的MySQL数据库获取BillCosby的值时,它将返回null ....在显示整个文件的代码之前,我只想弄清楚PDO是否有效完美,如果我要给变量$ username_notes直接赋予'BillCosby'的值,我将遍历整个数据库,则只有在我有$ _POST ['nameNotes']时,它才返回null.在前面.
This would work and the response would be BillCosby. Now with that out of the way, when I try to get a value for BillCosby from my MySQL database using PDO it will return null....Before I show the code for the whole file I just want to make clear that the PDO works perfect, if I were to give the variable $username_notes the direct value of 'BillCosby' I would run through the database perfect, it only returns null if I have the $_POST['nameNotes']; in front.
getNotes.php:
getNotes.php:
$username_notes = $_POST['nameNotes'];
grabNotes($username_notes);
function grabNotes($xusername)
{
.....
$newUser = $xusername;
try {
# MySQL with PDO_MYSQL
$DBH = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch(PDOException $e) {
echo "I'm sorry, I'm afraid I can't do that.";
file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
}
$sql = "SELECT notes FROM csvdata WHERE username = :username";
$getmeminfo = $DBH->prepare($sql);
$getmeminfo->execute(array(':username' => $newUser));
$row = $getmeminfo->fetch(PDO::FETCH_ASSOC);
$notes = $row['notes'];
$returnArray = array( 'the_notes' => $row['notes'],);
echo json_encode($returnArray);
$DBH = null;
}
所以我的问题是,为什么我不能从PDO语句取回返回值?如果我告诉PDO语句$ .ajax文件所调用的文件中的名称-'BillCosby',它将非常完美.但是,如果我从$ .ajax通过$ _POST获得值,它将无法工作并返回null.有趣的是,我可以返回与发送时相同的值.
So my question is, why can I not get the return value back from the PDO statement? It will work perfect if I told the PDO statement the name - 'BillCosby' inside the file that the $.ajax file calls to. But it will not work and returns null if I get the value through $_POST from the $.ajax. the funny thing is I can return the same value that was sent in.
感谢您的陪伴!
推荐答案
尝试修整它:
$username_notes = trim( $_POST['nameNotes'] );
有时字符串中的空格会导致这种错误,并且可能很难发现它们.
Sometimes spaces in the string will cause this sort of error, and they can be hard to spot.
这篇关于从$ .ajax调用中检索参数的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!