Note that there are some explanatory texts on larger screens.

plurals
  1. PODynamic JavaScript Variables Via Click Event Handler Using PHP/SQL
    text
    copied!<p>I'm populating a select tag with options gathered by using PHP to import all rows of a certain field in an SQL table. A row in my table follows this format:</p> <pre><code>id | wcat | wtype | was | wcc | wbdmin | wbdmax </code></pre> <p>I've completed this part successfully but the next task at hand is what I'm having trouble with as I am a newbie when it comes to PHP and Javascript.</p> <p>Within my click event handler I define a variable 'wtype' which I set to the value of the select option:</p> <pre><code>wtype = $("select[name='wtype'] :selected").val() || 0; </code></pre> <p>What I wish to do after is to import the corresponding fields for the row with a matching 'wtype' and set them as their own variables, ie. 'was', 'wcc', 'wbdmin', &amp; 'wbdmax'. Afterwards I use these values to do some math, etc.</p> <p>After doing some research/reading, I am currently attempting the following in my js file after I define the 'wtype' variable (even though I don't really have a clue what I'm doing):</p> <pre><code>var data = {w : wtype}; var url = "get.php"; $.post(url, data).done(function(data) { var winfo = $.parseJSON(data); was = winfo[3]; wcc = winfo[4]; wbdmin = winfo[5]; wbdmax = winfo[6]; $("#result").html(winfo); }); </code></pre> <p>And in <code>get.php</code>:</p> <pre><code>&lt;?php $host = "****"; $dbname = "****"; $user = "****"; $pass = "****"; try { $conn = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass); } catch(PDOException $e) { echo $e-&gt;getMessage(); } $conn-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $name = $_POST["w"]; $sql = "SELECT wtype, was, wcc, wbdmin, wbdmax FROM items WHERE wtype='".$name."'"; $stmt = $conn-&gt;prepare($sql); $stmt-&gt;setFetchMode(PDO::FETCH_ASSOC); if ($stmt) { try { $stmt-&gt;execute(); while ($row = $stmt-&gt;fetch()) { $data[] = $row; } $data = json_encode($data); } catch (PDOException $e) { var_dump($e); } } ?&gt; </code></pre> <p>This obviously does not work as my math results in NaN/undefined whereas before with test variable values it worked.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload