mardi 29 mars 2016

Send unchecked checkbox value through ajax

I have a complex problem due to the generic function I wrote to save form data in mySQL. All forms are send through ajax after being serialized:

$('.suggestSave, .buttonSave').on('submit', function(e) {
        e.preventDefault();
        var data = $(this).serialize();
        ...

I'm then fetching all POST values by looping through the values and creating the data saved in the database:

        $data = array();

        foreach ($_POST as $param_name => $param_val) {
          if($param_name != 'action' && $param_name != 'patient' && $param_name != 'jsaction') {
            $name = sanitize($param_name);
            $value = sanitize($param_val);
            $data[$name] = $value;
          }
        }

Naturally, an unchecked checkbox won't be sent through. The problem being that if it's empty, I'd like to store the Int value 0 instead of 1 for this checkbox.

On the HTML side, I have a classic syntax

<input type="checkbox" value="1" name="c_name1" checked/>
<input type="checkbox" value="1" name="c_name2"/>

Any suggestions on how to deal with that problem ? In a one-checkbox-situation, I would check if the post value isset(), but since I'm getting the names and values by looping through... I'm out of ideas...




Aucun commentaire:

Enregistrer un commentaire