Turning PHP into JSON array when parsed in Javascript -
so, in order create page has dynamic html, following javscript code used:
function add0(text, value){ var x = document.getelementbyid("thingy"); var option = document.createelement("option"); option.text = text; option.value = value; x.add(option);} function add(text, value){ var x = document.getelementbyid("stuff"); var option = document.createelement("option"); option.text = text; option.value = value; x.add(option);} var c = 0; var value =<?php echo json_encode($toandfromr); ?>; var formula = <?php echo json_encode($formular); ?>; while(c < <?php echo $countr ?>){ add0(value[c], formula[c]); add(value[c], formula[c]); c++; }
this done after recieving $toandfromr
, $formula
sql query, in code :
$conn = mysqli_connect($servername, $username, $password, $dbname); if (!$conn) { die("connection failed: " . mysqli_connect_error()); } //declare variables $countr = null; $sql = "select * `convert`"; $drippage = mysqli_query($conn, $sql); //this counts number of rows if (mysqli_num_rows($drippage)) { $countr = mysqli_num_rows($drippage); } $toandfrom = mysqli_query($conn, "select toandfrom `convert`"); $toandfromr = null; $toandfromr = mysqli_fetch_all($toandfrom, mysqli_both); $formular = null; $formula = mysqli_query($conn, "select formula `convert`"); $formular = mysqli_fetch_all($formula, mysqli_both);
however, html gets shown [object object] in dropdown list, opposed actual values when regular php array used. there way fix this?
each text
, value
passed javascript functions object 2 properties (because you're using mysqli_both
fetch mode), eg
{"0": "some value", "toandfrom": "some value"}
you're attempting assign option
's text
, value
properties.
you appear running 3 queries when should running one.
mysqli_report(mysqli_report_error | mysqli_report_strict); $conn = new mysqli($servername, $username, $password, $dbname); $conn->set_charset('utf8'); $result = $conn->query('select `toandfrom` `text`, `formula` `value` `convert`'); $options = $result->fetch_all(mysqli_assoc);
and in javascript
var options = <?= json_encode($options) ?>; (var = 0, l = options.length; < l; i++) { add0(options[i].text, options[i].value); add(options[i].text, options[i].value); }
also, cut down on identical javascript functions add0
, add
passing <select>
id, eg
function add(selectid, text, value) { var x = document.getelementbyid(selectid); // , on }
with
add('thingy', options[i].text, options[i].value); add('stuff', options[i].text, options[i].value);
Comments
Post a Comment