Reputation:
I am trying to pass a javascript variable which I get when a button is clicked to php and then run a mysql query. 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. I have an org chart that is displayed using javascript based on all the info is saved in my db. 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. For example, delete the row in the db. What's the best way to do it?
Upvotes: 0
Views: 8425
Reputation: 15783
There's a bit of confusion here, the success
value stores a callback that gets called when the Ajax call is successful. To give you a simple example, let's say you have an Ajax call like this:
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
. In this page you do some computation and then return a value, in this case as 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. In your javascript, in the specified callback (that is success
), you get data
as an object that contains the PHP's $to_return
value. What you have written does not really makes sense since PHP is a server language and cannot be processed from the browser like JavaScript.
Upvotes: 3