0

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. Currently, I have successfully received the PHP back to the javascript using Ajax, but not able to sending the ServiceName to the PHP File. 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.

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.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Tom1299
  • 1
  • 1
  • 2
    There are many Q&A about sending JavaScript variables to PHP. See for example: http://stackoverflow.com/questions/1917576/how-to-pass-javascript-variables-to-php – trincot Apr 04 '17 at 08:14
  • Also note that trying `$.post` when you originally did a GET request won't work – adeneo Apr 04 '17 at 08:15
  • **Warning** your PHP code is susceptible to SQL injections. Do not concatenate variables with SQL, use parameterised queries instead: `sqlsrv_query("SELECT DefaultContact2 FROM tblServices WHERE ServiceName=?", array($service));` – jcaron Apr 04 '17 at 09:02
  • Thank you for your help guys. @Jcaron before I go live, I will ensure that I implement parameters, to prevent SQL injections. – Tom1299 Apr 05 '17 at 18:36

4 Answers4

0

You could send data using your Ajax request like so.

$.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
print_r($_POST);

/*
[
    "name" => "John",
    "location" => "Boston"
]
*/
?>
Marijan
  • 1,825
  • 1
  • 13
  • 18
0

You cannot pass the javascript's variable to php on same page.

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.

TheTom
  • 298
  • 3
  • 15
0

You can do it in a single Ajax call.

Remove from your code this line:

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

And modify a bit the Ajax call

$.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. But I don't know if your query01.php should accept to do now both actions in the same call.

NetVicious
  • 3,848
  • 1
  • 33
  • 47
0

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!

Tom1299
  • 1
  • 1