Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

insert JS variable in a PHP string

Here is my code:

function myFunction2(){
      var code = document.getElementById("vehicle").value;

      var aux = "<?php 
        $conn = oci_connect($_SESSION['user'], $_SESSION['pswd'], 'oracleps');
        $stid = oci_parse($conn,'select max(kmi) from 
                                lloguer where lloguer.codi_vehicle="+code+"');
               oci_execute($stid);
               $row = oci_fetch_array($stid, OCI_BOTH);
               $kmi=($row[0]);
               echo $kmi;
               ?>";

      document.getElementById("kilometres").value= aux;}

I'm trying (very new on this) to update the id="vehicle" value, which is a text input, by calling the onclick="myFunction2()". The main problem i find it's that inside the php string, it doesn't allow me to concat the string with the "code" var in between.

I've tried to cocant the whole 'document.getElementById("vehicle").value'
Also tried by using the concat JS method.

What shall I do?



Thank you!

like image 739
David Suarez Avatar asked Oct 18 '22 17:10

David Suarez


1 Answers

Yes you can achieve this,

  1. The file should be a .php file
  2. Keep it separate.

before entering into javascript you have to parse the value to a php variable first.

<?php 
$conn = oci_connect($_SESSION['user'], $_SESSION['pswd'], 'oracleps');
$stid = oci_parse($conn,'select max(kmi) from lloguer where lloguer.codi_vehicle="+code+"');
oci_execute($stid);
$row = oci_fetch_array($stid, OCI_BOTH);
$kmi=($row[0]);
?>

after this you are having the value in $kmi.

now the javascript part

<script type="text/javascript">
var aux = "<?php echo  $kmi; ?>";
</script>

The above can be used if you want to access a php variable values in javascript, the below you can retrieve data using ajax.


Keep this in a separate file say ajax.val.php

<?php 
    $conn = oci_connect($_SESSION['user'], $_SESSION['pswd'], 'oracleps');
    $stid = oci_parse($conn,'select max(kmi) from lloguer where lloguer.codi_vehicle="+code+"');
    oci_execute($stid);
    $row = oci_fetch_array($stid, OCI_BOTH);
    echo $row[0];
    ?>

in javascript

<script type="text/javascript">
$(document).ready(function(){
    $("#vehicle").change(function(e){
        $.ajax({
            url : "ajax.val.php",
            data:{
                v : $(this).val()
            },
            success: function(e){
                $("#kilometres").val(e);
            }
        });
    });
});
</script>
like image 195
itssajan Avatar answered Oct 21 '22 08:10

itssajan