f7n February 2016

How to build an SQL query from HTML checkboxes?

I need to create a query builder for SQL, where you can choose query constraints via HTML checkboxes. Each checkbox has a name,used for a column name (e.g ActorName), and a value for the column value (like Tom Hanks).

I'm having trouble deciding what is the best way to do this. I've tried adding/removing to a JavaScript object, and then iterating through each key-value pair, i.e each ActorName, each DirectorName, and append them to the WHERE constraint in SQL, but as the checkbox names are not unique, i.e there are many Actors, Genres etc, it complicates things. Right now, I'm using this method:

https://jsfiddle.net/Lompm0ew/5/

On checkbox checked, add the checkbox's name and value to a JS object, with the ActorName as the object key (as this will always be unique), and the checkbox name as the object value. I have a feeling this is bad practice, and I'm sure there is a better way to achieve my goal, but I'm out of ideas.

can anyone recommend a better method of building a query from checkboxes?

Answers


Xenofexs February 2016

You can use "serialize" for get and send data with Ajax

First, add a form balsise in your 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);
            }
         

Post Status

Asked in February 2016
Viewed 1,402 times
Voted 6
Answered 1 times

Search




Leave an answer