ajay kumar ajay kumar - 10 days ago 6
Javascript Question

how to assign php variable value to the javascript variable

//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)


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);
}
}

Answer

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>
Comments