将Javascript变量传递给PHP文件

时间:2017-04-04 08:11:22

标签: javascript php jquery ajax

我想知道你是否可以提供帮助。我试图将变量传递给PHP文件,然后运行SQL查询,使用该变量,然后将结果作为变量传递给javascript。目前,我已成功使用Ajax将PHP返回到javascript,但无法将ServiceName发送到PHP文件。文件保持独立是至关重要的。另外,为了澄清我已经替换了某些部分以保护隐私,但是,它们是正确的并且在代码中工作。我已经使用了$ _GET方法,但是,我只能获取javascript来访问新窗口而不返回PHP变量。

我目前的代码如下:

// 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);            
?>

非常感谢任何帮助。

4 个答案:

答案 0 :(得分:0)

您可以使用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);
    }
});

然后在PHP中访问发送的数据:

<?php
print_r($_POST);

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

答案 1 :(得分:0)

您无法在同一页面上将javascript的变量传递给php。

您可以使用POST或GET方法调用ajax,然后将操作数据发送回浏览器并将其存储在javascript的对象或变量中。

答案 2 :(得分:0)

您可以在单个Ajax调用中执行此操作。

从代码中删除此行:

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

修改一下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
      }
});

我为Ajax调用中的Get添加了相同的变量名。但是我不知道你的query01.php是否应该接受在同一个调用中同时执行这两个操作。

答案 3 :(得分:0)

谢谢你们的帮助。只是觉得它会很有用,如果我最后发布了我的内容,不管它是否是正确的方式,它肯定完成了这项工作。

// 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.

再次感谢您的回复!