title: Saving data to database using Jquery
body: <p>I'm creating a browser RPG game. I want to allow a user to save their current stats by updating the mysql db without having to reload the page... So I thought jquery could help. </p>
  
  <p>The user will not be adding their own stats. The stats are generated through user actions, such as solving a challenge. I want the user to be able to save those updated stats to the database whenever they would like.</p>
  
  <p>The issues are:</p>
  
  <ul>
  <li><p>the jQuery is outputting the <code>echo "saved..." . $stats . ", " . $stats2;</code> before I click the Save button. </p></li>
  <li><p>When I click save, the database field isn't being updated.</p></li>
  </ul>
  
  <p>I'm wondering why this isn't working. When I click save, the stats fields shouldn't be <code>0</code>, but should be the stats that are shown- <code>11</code>. The database fields should also be updated.</p>
  
  <p>For testing purposes, I've just created js variable <code>var stats</code> that is updated when the arrow keys are pressed. </p>
  
  <p>I call the function updateHUD() to do <code>$('#stats').html(stats);</code> which updates the HTML.</p>
  
  <pre><code>function updateHUD() {  
      $('#stats').html(stats);
  }
  </code></pre>
  
  <p>Then updateHUD is called after arrow key is pressed.</p>
  
  <hr>
  
  <p><strong>HTML</strong></p>
  
  <pre><code>&lt;div class="span12"&gt;
      &lt;button onclick="saveData(stats)" name="input" value=""&gt;Save Data&lt;/button&gt;
          &lt;br /&gt;&lt;span id="output"&gt;&lt;/span&gt;&lt;br /&gt;
          &lt;ul&gt;
          &lt;li&gt;&lt;b&gt;Stats 1:&lt;/b&gt;     &lt;span id="stats"&gt;&lt;/span&gt;    &lt;/li&gt;
          &lt;/ul&gt;
  &lt;/div&gt;
  </code></pre>
  
  <hr>
  
  <p><strong>jQuery</strong></p>
  
  <pre><code>//Pass saved data to store in DB
  $(document).ready(function() {
      saveData();
  });
  
  
  function saveData() {     
     $.get("php/CRUD.php", {"_input" : $('input[name=input]').val()},
          function(returned_data) {
              $("#output").html(returned_data);
          }
      );
  }
  </code></pre>
  
  <hr>
  
  <p><strong>PHP</strong></p>
  
  <pre><code>&lt;?php
  //store all player data in array and save to/update db
  include 'DbConnect.php';
  session_start();
  
  $stats = (isset($_GET['_input']) ? ($_GET['_input']) : 0); 
  
  $formvars = array();
  array_push($formvars, $stats);      
  
  echo $stats;
  echo $_SESSION['username'];
  
  
  $qry = 'UPDATE users SET stats="'.$stats.'" WHERE username="' . $_SESSION['username'] . '"';    
  $mysqli-&gt;query($qry) or die(mysqli_error($mysqli));
  
  echo "saved..." . $stats;
  mysqli_close($mysqli);
  ?&gt;
  </code></pre>
  
  <hr>
  
  <p><strong>Output</strong></p>
  
  <pre><code>saved...0 //this should be 11
  Stats 1: 11
  </code></pre>