1

I am trying to get a php variable from url using $_REQUEST to javascript so I can send it through Ajax.

At The top of my page I have:

<?php
  include_once('../php/connection.php');
  include_once('../php/getDiagnosis.php');
  $pid = $_REQUEST['pid'];

?>

And in the Java Script Part I have:

  <script src="../js/history.js"></script>

And in history.js:

var addHistory = function()
{
  var patient_medication = $("#patient_medicationn").val();
  var disease = $("#disease").val();
  var patient_side_effect = $("#patient_side_effect").val();

  var pid = '<?php echo $pid;?>';
  console.log(pid);

  if(disease=="select")
  {
    $("#disease").css('border-color', 'red');
    $("#disease").focus();
  }

  else
  {
    $.ajax({
      url: '../php/history.php',
      data: {pid: pid, patient_medication: patient_medication, disease: disease, patient_side_effect: patient_side_effect},
      type: 'POST',
      dataType: 'TEXT',

      success:function(resp)
      {

      },
      error:function(resp)
      {
        alert("Information have not been added, please try again");
      }
    })
  }
}
$(document).ready(function()
{

  $("#add_history").on('click', addHistory);
  $("#patient_medication").on('keypress', function(event)
  {
    if(event.which==13)
    {
        $("#add_history").click();
    }
  })
  $("#patient_side_effect").on('keypress', function(event)
  {
    if(event.which==13)
    {
        $("#add_history").click();
    }
  })
});

The result in the console is:

alim1990
  • 4,656
  • 12
  • 67
  • 130
  • Your JS file is probably not compiled server-side, so the PHP code is not executed. – Peter M. Jun 23 '17 at 11:06
  • 1
    Is there a way to fix it ? – alim1990 Jun 23 '17 at 11:07
  • You should try this link. It will more sortable. [https://stackoverflow.com/questions/9653651/including-php-variables-in-an-external-js-file](https://stackoverflow.com/questions/9653651/including-php-variables-in-an-external-js-filehttp://) – Ankesh Vaishnav Jun 23 '17 at 11:22
  • There´s a good way to fix it - kindly check my answer. – Curious Mind Jun 23 '17 at 11:23
  • Please make sure your history.php checks if the user making the request have permission to see the history they're asking for. Otherwise anyone would be able to get the history just by having the pid (or guessing it). You can do this with session variables. – Marcelo Staudt Jun 23 '17 at 11:49

5 Answers5

2

Your JS file is probably not compiled server-side, so the PHP code is not executed.

One way to work around is, is using a hidden field.

In your HTML page (which probably is compiled) you can do something like this:

<input type="hidden" name="someField" id="someField" value="<?php echo $pid; ?>">

In your JS file, you can do this:

var pid = $('#someField').val();
Peter M.
  • 1,240
  • 2
  • 9
  • 25
1

You cannot do this way. The possible way is to create a global variable which is accessible from your JS file. Before this line

<script src="../js/history.js"></script>

add this

<script>var pid = '<?php echo $pid;?>';</script>

and now pid is available in the JS file.

Arpad Hollo
  • 201
  • 1
  • 9
1

As @Peter m said, your .js fileso are not parsed by default, you can change the Apache configuration to parse .js files (not recomended). What I would do, just make your variable global and define it in the php file or pass the variable as an argument to the function.

1

You can do it with 3 minor changes:

Change this:

<script src="../js/history.js"></script> 

to this:

<script type="text/javascript" src="../js/history.php?pid=$pid"></script>

And then rename history.js to history.php.

EDIT START

First 4 lines of your previous js file, now history.php should be:

<?php
    header('Content-Type: application/javascript');
    $pid = $_GET['pid'];
?>

EDIT END

Test it - it should work.

There is no need to reconfigure apache to parse js - also parsing all js files as php files would greatly increase server load.

This way, it will be seen by the browser as a js file and there´s no extra load on the server.

Curious Mind
  • 659
  • 10
  • 26
1

For security and code maintenance issues never mix server-side with client-side code in such a way, Pass the variable as method attribute instead

JS:

var addHistory = function(pId){
   // treat as attribute
   // ...
}

Initiate JS:

$(document).ready(function(){


// some generic function used to parse url
// You can google JS url parser library for more functionality
function getQueryParam(url, key) {
  var queryStartPos = url.indexOf('?');
  if (queryStartPos === -1) {
    return;
  }
  var params = url.substring(queryStartPos + 1).split('&');
  for (var i = 0; i < params.length; i++) {
    var pairs = params[i].split('=');
    if (decodeURIComponent(pairs.shift()) == key) {
      return decodeURIComponent(pairs.join('='));
    }
  }
}
// use on click, bind clicks to body avoiding future event collisions
$('body').on('click','#add_history', addHistory, function(){
   // get parameter from url
   var pId = getQueryParam(window.location, 'pid');
   addHistory(pId); 
});

});
George Dryser
  • 322
  • 1
  • 7