How to pass javascript variable to php using ajax

后端 未结 1 679
一个人的身影
一个人的身影 2021-01-26 12:02

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({
         


        
相关标签:
1条回答
  • 2021-01-26 12:33

    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.

    0 讨论(0)
提交回复
热议问题