[英]Passing session variable through AJAX to PHP file
My goal is to pass $userId
variable (which contains the session variable), through an ajax statement, into a php file that contains an echoed form. 我的目标是通过ajax语句将
$userId
变量(包含会话变量)传递到包含回显表单的php文件中。 The purpose is so that when the form is submitted the session variable can be inserted into the database and then used as a way to identify which entries where done by which users. 目的是在提交表单时,可以将会话变量插入到数据库中,然后将其用作识别哪些用户完成哪些条目的方式。
Im having a bit of trouble getting the variable data to go to the ajax statement. 我在将变量数据转到ajax语句时遇到了一些麻烦。 What am i doing wrong?
我究竟做错了什么?
<?php
session_start();
if(isset($_SESSION['userid'])) {
$userId = mysql_real_escape_string($_SESSION['userid']);
echo $userId;
echo ' (irrelevant code)...
//button that loads form via ajax...
<a href="#" class="small button radius expand" onClick="showAdd(\'$userId\');return false;">Add URL</a>
(irrelevant code)... ';
}
AJAX code: AJAX代码:
function showAdd(str) {
$('#response').html('Processing Request. Please wait a moment...');
var userId = str;
alert (userId);
$.ajax({
type: "POST",
url: "addUrlForm.php",
data: "userId=" + str,
success: function(msg) {
$('#response').empty();
$('#content01').html(msg).show();
},
error: function () {
alert('error');
}
});
};
EDIT: I took your suggestion (thank-you) and it some-what helped. 编辑:我接受了你的建议(谢谢你),它有所帮助。 Now the alert is returning "$userId" variable as a string.
现在警报将“$ userId”变量作为字符串返回。 How do I make it be recognised as a variable containing the session data, not as a string?
如何将其识别为包含会话数据的变量,而不是字符串? I tried "showAdd($userId)" but console is telling me $userId is not defined?.
我试过“showAdd($ userId)”,但是控制台告诉我$ userId没有定义?
Since you're sending the userId
as a parameter to the showAdd()
function you should change your code to: 由于您将
userId
作为参数发送到showAdd()
函数,因此您应该将代码更改为:
function showAdd(str) {
var userId = str;
// ...
}
or simply rename the parameter to userId
: 或者只是将参数重命名为
userId
:
function showAdd(userId) {
// use userId here
]
To make you above code send the correct userId
and not the string $userId
to the function you should wrap your output string in double quotes or output it directly: 为了使您在上面的代码中发送正确的
userId
而不是字符串$userId
,您应该将输出字符串$userId
双引号或直接输出:
echo '<a href="#" class="small button radius expand" onClick="showAdd('.$userId.');return false;">Add URL</a>';
or: 要么:
echo "<a href='#' class='small button radius expand' onClick='showAdd($userId);return false;'>Add URL</a>";
I do not understand why would you use $(this)
when the userid
is already present and is passed as function parameter. 我不明白为什么当
userid
已经存在并且作为函数参数传递时你会使用$(this)
。
Change this: 改变这个:
var userId = $(this).attr('userId');
To: 至:
var userId = str;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.