0

I am selecting input values from the database and I want to send it to the javascript function addVal() so that I can retrieve this value. I do not want to use echo. It is not working right now and I don't know how I can make it work.

<h1>trial,</h1>
 <div id ="val">   </div>
  <?php
 $name = $_POST['postname'];

$host = 'localhost';
$user = 'root';
$pass = 'root';
$db_name="big";



$conn = new mysqli($host, $user, $pass, $db_name);


if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
echo "connected";
$sql = "SELECT input FROM trial_db";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while( $row = $result->fetch_assoc()) {
        $value = $row['input'];
        addVal ($value);
    }

}
?>

<script>
    function addVal (value){
        document.getElementById("val").innerHTML+= value ;
    }
</script>
Sherif
  • 11,786
  • 3
  • 32
  • 57
CS Student
  • 83
  • 11
  • 1
    Javascript is Javascript and PHP is PHP. You can't access functions on each language. For further explanation refer for this post [How to pass variables and data from PHP to JavaScript?](http://stackoverflow.com/a/23740549/3559533) – Terinah14 Sep 07 '16 at 00:33

1 Answers1

1

Calling js function from php will not work remove that code from php.

And change in js.

<script>
  function addVal (){
     var value = "<?php echo $value; ?>";
    document.getElementById("val").innerHTML+= value ;
  }
</script>

Will only work if js and php codes are in same php file.

Niklesh Raut
  • 34,013
  • 16
  • 75
  • 109
  • It will also only work if `$value` is a relatively ordinary type of value and doesn't contain quotes. – tadman Sep 07 '16 at 00:57
  • it worked but it only have the last value from the database. I need as $value = $row['input']; iterate my database I send each value to the js function. how can I do that ?? (that is why I wanted to call addVal() in the loop) please help! @Rishi – CS Student Sep 07 '16 at 17:21