Category Archives: ajax

Caricare dati jSON con jQuery, PHP e MySQL!

In questo articolo vedremo come popolare una select, ottenendo i valori jSON con jQuery da uno script PHP che riceve i dati da un database MySQL.

CODICE HTML

  1.  
  2. <form>
  3. Fruit:
  4. <select name="name" id="fruitName">
  5. <option>Apple</option>
  6. <option>Banana</option>
  7. <option>Orange</option>
  8. <option>Pear</option>
  9. </select>
  10. Variety:
  11. <select name="variety" id="fruitVariety">
  12. </select>
  13. </form>
  14.  

CODICE JQUERY

  1.  
  2. function populateFruitVariety() {
  3.  
  4. $.getJSON('/fruit-varities.php', {fruitName:$('#fruitName').val()}, function(data) {
  5.  
  6. var select = $('#fruitVariety');
  7. var options = select.attr('options');
  8. $('option', select).remove();
  9.  
  10. $.each(data, function(index, array) {
  11. options[options.length] = new Option(array['variety']);
  12. });
  13.  
  14. });
  15.  
  16. }
  17.  
  18. $(document).ready(function() {
  19.  
  20. populateFruitVariety();
  21. $('#fruitName').change(function() {
  22. populateFruitVariety();
  23. });
  24.  
  25. });
  26.  

CODICE PHP

  1.  
  2. $dsn = "mysql:host=localhost;dbname=[NOME DB]";
  3. $username = "[TUO USERNAME]";
  4. $password = "[TUA PASSWORD]";
  5.  
  6. $pdo = new PDO($dsn, $username, $password);
  7.  
  8. $rows = array();
  9. if(isset($_GET['fruitName'])) {
  10. $stmt = $pdo->prepare("SELECT variety FROM fruit WHERE name = ? ORDER BY variety");
  11. $stmt->execute(array($_GET['fruitName']));
  12. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  13. }
  14. echo json_encode($rows);
  15.  

Un modo semplice per selezionare tutte le checkbox con jQuery!

Grazie a questo tutorial imparerete come selezionare / deselezionare tutte le checkbox presenti in un fieldset.

  1.  
  2. <fieldset>
  3. // these will be affected by check all
  4. <div><input type="checkbox" id="checkall"/> Check all</div>
  5. <div><input type="checkbox"/> Checkbox</div>
  6. <div><input type="checkbox"/> Checkbox</div>
  7. <div><input type="checkbox"/> Checkbox</div>
  8. </fieldset>
  9. <fieldset>
  10. // these won't be affected by check all; different fieldset
  11. <div><input type="checkbox"/> Checkbox</div>
  12. <div><input type="checkbox"/> Checkbox</div>
  13. <div><input type="checkbox"/> Checkbox</div>
  14. </fieldset><fieldset>
  15. </fieldset>