简体   繁体   English

将Javascript变量传递到PHP文件

[英]Passing Javascript Variable to PHP File

I was wondering if you could help. 我在想,如果你能帮助。 I am attempting to pass a variable to a PHP file, then run a SQL query, using that variable, then pass back the result as a variable to the javascript. 我试图将变量传递给PHP文件,然后使用该变量运行SQL查询,然后将结果作为变量传递回javascript。 Currently, I have successfully received the PHP back to the javascript using Ajax, but not able to sending the ServiceName to the PHP File. 目前,我已经使用Ajax成功地将PHP返回到javascript,但是无法将ServiceName发送到PHP文件。 It is essential that the files stay separate. 重要的是,该文件保持分离。 Also just to clarify I have replaced certain sections for privacy, however, they are correct and working in the code. 也只是为了澄清我已经取代某些部分的隐私,但是,他们是正确的,在代码中工作。 I have also used a $_GET method already, however, I could only get the javascript to access a new window and not return the PHP variable. 我也已经使用了$ _GET方法,但是,我只能获取JavaScript来访问新窗口,而不能返回PHP变量。

My current code is as follows: 我当前的代码如下:

// If the user changes the ServiceID field.
if (sender.getFieldName() == 'ServiceID')
  // Declare the value of the new Service name and save it in the variable A.
  a = sender.getValue();

{     
  // if it equals a new variable.
  if (sender.getValue() == a) {
    // Place it within the URL, in order for it to be processed in the php        code.
    window.location.href = "http://IP/development/Query01.php?service=" + a;

    // Attempted code
    // echo jason_encode(a);
    //    $.ajax({var service = a;
    //  $.post('http://IP/development/Query01.php', {variable: service});
    //  }

    //use AJAX to retrieve the results, this does work if the service name        is hard coded into the PHP.   
    $.ajax({
      url: "http://IP/development/Query01.php",
      dataType: "json", //the return type data is jsonn
      success: function(data) { // <--- (data) is in json format
        editors['Contact2'].setValue(data);
        //alert(data);
        //parse the json data
      }
    });
  }
}
}
<?php
  $serverName = "SeverIP"; //serverName\instanceName, portNumber (default is   1433)
  $connectionInfo = array( "Database"=>"DatabaseName", "UID"=>"Username",  "PWD"=>"Password
  $conn = sqlsrv_connect( $serverName, $connectionInfo);
  $service = $_GET['service'];

  if ($conn) 
  {
    //echo "Connection established.<br />";
  } 
  else 
  {
    echo "Connection could not be established.<br />";
    die( print_r( sqlsrv_errors(), true));
  } 

  $sql = ("SELECT DefaultContact2 FROM tblServices WHERE ServiceName =  '$service'");
  $stmt = sqlsrv_query($conn, $sql);

  if ($stmt === false) 
  {
    die( print_r( sqlsrv_errors(), true));
  }
  while ($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)) 
  {
    $dC2 = $row['DefaultContact2'];
  }
  echo json_encode ($dC2);
  sqlsrv_free_stmt( $stmt);            
?>

Any help would be greatly appreciated. 任何帮助将不胜感激。

You could send data using your Ajax request like so. 您可以像这样使用Ajax请求发送数据。

$.ajax({
    url: "http://IP/development/Query01.php",
    method: "POST" // send as POST, you could also use GET or PUT,
    data: { name: "John", location: "Boston" }
    dataType: "json",
    success: function(data) {
        editors['Contact2'].setValue(data);
    }
});

Then in PHP access the sent data: 然后在PHP中访问发送的数据:

<?php
print_r($_POST);

/*
[
    "name" => "John",
    "location" => "Boston"
]
*/
?>

You cannot pass the javascript's variable to php on same page. 您无法在同一页面上将javascript的变量传递给php。

You can do this with ajax call with POST or GET method, and then you can send the manipulated data back to you browser and store it in your javascript's object or variable. 您可以使用POST或GET方法进行ajax调用,然后将处理后的数据发送回浏览器并将其存储在javascript的对象或变量中。

You can do it in a single Ajax call. 您可以在单个Ajax调用中完成此操作。

Remove from your code this line: 从代码中删除以下行:

window.location.href = "http://IP/development/Query01.php?service=" + a;

And modify a bit the Ajax call 并修改一下Ajax调用

$.ajax({
      type: 'GET'
      data : {
            service: sender.getValue();
      },
      url: "http://IP/development/Query01.php",
      dataType: "json", //the return type data is jsonn
      success: function(data){ // <--- (data) is in json format
            editors['Contact2'].setValue(data);
            //alert(data);
            //parse the json data
      }
});

I put the same variable name for the Get in the Ajax call. 我在Ajax调用中为Get设置了相同的变量名。 But I don't know if your query01.php should accept to do now both actions in the same call. 但是我不知道您的query01.php是否应该接受在同一调用中同时执行两个操作。

Thank you guys for your help. 谢谢你们的帮助。 Just thought it would be useful, if I posted of what I went with in the end, regardless of whether it is the right way, it certainly done the job. 只是认为这会很有用,如果我发布最后的内容,不管它是不是正确的方法,它肯定都能完成工作。

// If the user changes the ServiceID field.
if (sender.getFieldName() == 'ServiceID')

{      
    // Variable Declaration
    serviceName = sender.getValue();

    {
      // Use JQuery.Ajax to send a variable to the php file, and return the   result.
      $.ajax({
      // Access the PHP file and save the serviceName variable in the URL, to allow the $_GET..
      // method to access the javascript variable to apply it within the SQL  Query.
         url: "http://ServerName/development/DefaultContact1.php?service=" +  serviceName,
         // retrieve the result, using json.
         dataType: "json", // the return type data is jsonn
         success: function(data)// <--- (data) is in json format
                  {
                  // pre-fill the contact1 field with the result of the PHP file.
                  editors['Contact1'].setValue(data);
                  }
             // End of Ajax Query    
             });
     // End of function to prefill Contact1 field.

Thank again for your responses! 再次感谢您的回复!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM