-5

//here str is a variable, i just trying to assign php variable to the srt variable but i am getting an error i.e:-

Parse error: syntax error, unexpected 'var' (T_VAR)

 <script>
 <?php 
while($rowss = mysql_fetch_array($result2, MYSQL_ASSOC)){ 
  ?>  
    var str = <?php echo $rowss["ingredient"];?>;
    var str_array = str.split(',');
    for(var i = 0; i < str_array.length; i++) {
        // Trim the excess whitespace.
        str_array[i] = str_array[i].replace(/^\s*/, "").replace(/\s*$/, "");
        // Add additional code here, such as:
        var opt = document.createElement('option');
        opt.innerHTML = str_array[i];
        opt.value = str_array[i];
        sel.appendChild(opt);
    }
}
</script>
ajay kumar
  • 11
  • 1
  • 4

2 Answers2

0
?>
<script>
<?php
while($rowss = mysql_fetch_array($result2, MYSQL_ASSOC)){   
?>
var str = '<?=$rowss["ingredient"]?>';
var str_array = str.split(',');
    for(var i = 0; i < str_array.length; i++) {
        // Trim the excess whitespace.
        str_array[i] = str_array[i].replace(/^\s*/, "").replace(/\s*$/, "");
        // Add additional code here, such as:
        var opt = document.createElement('option');
        opt.innerHTML = str_array[i];
        opt.value = str_array[i];
        sel.appendChild(opt);
    }
<?php
}
?>
</script>
Shaun Parsons
  • 362
  • 1
  • 11
0

An alternative approach might be to generate an array in PHP with all the ingredients and later assign that as a variable in javascript.

<?php
    $strs = array();
    while( $rowss = mysql_fetch_array( $result2, MYSQL_ASSOC ) ){
        $strs[]=$rowss["ingredient"];
    }
?>

<script>
    <?php
        echo "var strs=JSON.parse( " . json_encode( $strs ) . " );\n";
    ?>
    for( var n in strs ){

        var str = strs[ n ];
        var str_array = str.split(',');

        for( var i = 0; i < str_array.length; i++ ) {
            str_array[i] = str_array[i].replace(/^\s*/, "").replace(/\s*$/, "");
            var opt = document.createElement('option');
                opt.innerHTML = str_array[i];
                opt.value = str_array[i];
            sel.appendChild(opt);
        }
    }
</script>
Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46