javascript - How to build an SQL query from HTML checkboxes? -
i need create query builder sql, can choose query constraints via html checkboxes. each checkbox has name,used column name (e.g actorname), , value column value (like tom hanks).
i'm having trouble deciding best way this. i've tried adding/removing javascript object, , iterating through each key-value pair, i.e each actorname, each directorname, , append them where
constraint in sql, checkbox names not unique, i.e there many actors, genres etc, complicates things. right now, i'm using method:
https://jsfiddle.net/lompm0ew/5/
on checkbox checked, add checkbox's name , value js object, actorname object key (as unique), , checkbox name object value. have feeling bad practice, , i'm sure there better way achieve goal, i'm out of ideas.
can recommend better method of building query checkboxes?
you can use "serialize" , send data ajax
first, add form balsise in html code
example :
<form> <div id="checkboxes"> <label> <input type="checkbox" value="tom hanks" name="actorname[]">tom hanks</label> <label> <input type="checkbox" value="tim allen" name="actorname[]">tim allen</label> <label> <input type="checkbox" value="don rickles" name="actorname[]">don rickles</label> <label> <input type="checkbox" value="jim varney" name="actorname[]">jim varney</label> <label> <input type="checkbox" value="wallace shawn" name="actorname[]">wallace shawn</label> <label> <input type="checkbox" value="fantasy" name="genrename[]">fantasy</label> <label> <input type="checkbox" value="comedy" name="genrename[]">comedy</label> <label> <input type="checkbox" value="children" name="genrename[]">children</label> <label> <input type="checkbox" value="animation" name="genrename[]">animation</label> <label> <input type="checkbox" value="adventure" name="genrename[]">adventure</label> <label> <input type="checkbox" value="usa" name="countryname">usa</label> </div> </form>
your javascript :
jquery(document).ready(function($){ $(':checkbox').change(function() { senddata(); }); }) function senddata () { var $form = $('form'); $.ajax({ url : 'ajax.php', data: $form.serialize(), async : false, success : function(response){ console.log(response); } }); }
your ajax.php
<?php var_dump($_request);
show :
array(2) { ["actorname"]=> array(3) { [0]=> string(9) "tim allen" [1]=> string(10) "jim varney" [2]=> string(13) "wallace shawn" } ["genrename"]=> array(1) { [0]=> string(9) "animation" } }
each time click on checkbox, send data ajax.php. so, can make query server side
edit : sorry i've forgot : can rename checkbox name send array
<label> <input type="checkbox" value="tom hanks" name="actorname[]">tom hanks</label> <label> <input type="checkbox" value="tim allen" name="actorname[]">tim allen</label> <label>
Comments
Post a Comment