[英]How to pass javascript variable to php using ajax
I am trying to pass a javascript variable which I get when a button is clicked to php and then run a mysql query. 我试图传递一个JavaScript变量,当单击一个按钮到php然后运行一个mysql查询时,我得到了这个变量。 My code:
我的代码:
function ajaxCall(nodeID) {
$.ajax({
type: "POST",
url: "tree.php",
data: {activeNodeID : nodeID},
success: function(data) {
alert("Success!");
}
}
);
}
function onButtonClick(e, data) {
switch (data.name) {
case "add":
break;
case "edit":
break;
case "delete":
nodeid = data.context.id;
ajaxCall(nodeid);
//query
break;
}
}
<?php
if (isset($_POST['activeNodeID'])) {
$nodeid = $_POST['activeNodeID'];
}
else {
$nodeid = 0;
}
?>
I haven't done this before, so I am not sure why this doesn't work. 我之前没有做过,所以我不确定为什么这行不通。 Any suggestions?
有什么建议么? EDIT: Maybe I haven't explained myself well enough.
编辑:也许我还没有很好地解释自己。 I realise that php is server side and javascript is client side.
我意识到php是服务器端,而javascript是客户端。 I have an org chart that is displayed using javascript based on all the info is saved in my db.
我有一个基于Java的组织结构图,它基于所有信息保存在我的数据库中。 What I need to do is: when one of the javascript buttons is clicked (edit, delete, add) get the ID of the active node and use it as variable in php to run query.
我需要做的是:单击javascript按钮之一(编辑,删除,添加)时,将获得活动节点的ID,并将其用作php中的变量以运行查询。 For example, delete the row in the db.
例如,删除数据库中的行。 What's the best way to do it?
最好的方法是什么?
There's a bit of confusion here, the success
value stores a callback that gets called when the Ajax call is successful. 这里有些混乱,
success
值存储一个回调,该回调在Ajax调用成功时被调用。 To give you a simple example, let's say you have an Ajax call like this: 为了给您提供一个简单的示例,假设您有一个如下的Ajax调用:
function ajaxCall(nodeID) {
$.ajax({
type: "POST",
url: "tree.php",
data: {activeNodeID : nodeID},
success: function(data) {
console.log(data.my_message);
}
});
This calls a PHP page called tree.php
. 这将调用一个名为
tree.php
的PHP页面。 In this page you do some computation and then return a value, in this case as JSON. 在此页面中,您需要进行一些计算,然后返回一个值,在这种情况下为JSON。 So the page looks like this (note that I'm keeping it simple, you should validate input values, always):
因此页面如下所示(请注意,我保持简单,您应该始终验证输入值):
$v = $_REQUEST['activeNodeID'];
$to_return = "the value sent is: " . $v;
return json_encode(array('my_message' => $to_return));
This simple PHP page returns that string as a JSON. 这个简单的PHP页面以JSON形式返回该字符串。 In your javascript, in the specified callback (that is
success
), you get data
as an object that contains the PHP's $to_return
value. 在您的javascript中,在指定的回调中(即
success
),您将data
作为包含PHP的$to_return
值的对象来$to_return
。 What you have written does not really makes sense since PHP is a server language and cannot be processed from the browser like JavaScript. 您编写的内容没有任何意义,因为PHP是一种服务器语言,无法像JavaScript这样从浏览器进行处理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.