Insert JS variable into 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 am trying (new to this) to update the id = "vehicle" value, which is text input, by calling onclick = "myFunction2 ()". The main problem, I find that inside the php line this does not allow me to concat the line with the "code" var between them.

I tried to compose the entire document document.getElementById ("vehicle"). value '
Also tried using the concat JS method.

What should I do?



Thanks!

+4
source share
1 answer

Yes you can achieve this

  • File must be .php
  • Keep it separate.

javascript 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);
$kmi=($row[0]);
?>

$kmi.

javascript

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

, php javascript, ajax.


, 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];
    ?>

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>
+3

Source: https://habr.com/ru/post/1624900/


All Articles