简体   繁体   中英

How to send an checkbox array and some other values with ajax jquery post through PHP MVC

I'm trying to send data into database using AJAX/JQUERY/PHP(MVC);

I have a table with loads of data; the table contain checkboxes to check rows which can be sent to database.

For the View file; Im trying to send data like this:

Edited

<form action="<?php echo URL ?>etudiants/affectation" method="POST" id="affectStudents"  class='form-vertical'>
    <div class="span3">
        <div class="control-group">
            <div class="input-append">
                <select name="id_salle" id="id_salle" class='input-medium'>
                    <option value="0">«Choisir Salle»</option>
                    <?php foreach($this->fetchSalle AS $key => $value): ?>
                    <option value="<?php echo $value['id_salle'] ?>">
                    <?php echo $value['intitule_salle']; ?>
                    => C: <?php echo $value['capacite']; ?>
                    => M: <?php echo $value['marge']; ?>
                    </option>
                <?php endforeach; ?>
                </select>
                <button class="btn" type="submit"> Affecter</button>
            </div>
        </div>
    </div>
    <div class="box-content nopadding">
        <table class="table table-hover table-nomargin table-bordered dataTable dataTable-nosort" data-nosort="0">
            <thead>
                <tr class='thefilter'>
                    <th class='with-checkbox'>
                    <input type="checkbox" name="check_all" id="check_all"></th>
                    <th>Code Etud.</th>
                    <th>Filière</th>
                    <th>Nom et Prénom</th>
                    <th>CIN</th>
                    <th>Tel</th>
                    <th>Email</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach($this->fetchEtudiants AS $value): ?>
                <tr>
                    <td class="with-checkbox">
                    <input type="checkbox" name="id_etudiants[]" value="<?php echo $value['id_etudiant']; ?>" class="check_id" id="check_id">
                    </td>
                    <td><?php echo $value['code_etudiant']; ?></td>
                    <td><?php echo $value['intitule_filiere']; ?></td>
                    <td><?php echo $value['nom']; ?> 
                         <?php echo $value['prenom']; ?>
                    </td>
                    <td><?php echo $value['cin']; ?></td>
                    <td><?php echo $value['tel']; ?></td>
                    <td><?php echo $value['email']; ?></td>
                </tr>
            <?php endforeach; ?>    
        </tbody>
    </table>
    <input type="hidden" name="csem" value="<?php echo @$_GET['csem'] ?>">
    <input type="hidden" name="cses" value="<?php echo @$_GET['cses'] ?>">
    <input type="hidden" name="cfil" value="<?php echo @$_GET['cfil'] ?>">
    <input type="hidden" name="cmod" value="<?php echo @$_GET['cmod'] ?>">
</form>

Controller file

etudiants.php

class Etudiants extends Controller {

    function __construct(){
        parent::__construct();          
    }
    public function index(){        
        $this->view->render('etudiants/index');
    }

    function affectation(){
        $this->model->affectation();
    }   
}

etudiants_model.php

class Etudiants_Model extends Model
    {
    public function __construct(){
        parent::__construct();
    }
    public function affectation(){
        $students[] = $_POST['id_etudiants'];
        $id_salle   = $_POST['id_salle'];

        for ($i=1; $i <= strlen($students) ; $i++) {
            $stmt = $this->db->prepare("INSERT INTO exam_salles (id_student, id_salle) VALUES(?,?)");
            $stmt->execute(array($students[$i], $id_salle));
        }

        if($stmt == TRUE){
            echo "good";
        }else{
            echo "wrong";
        }
    }
}

for the JS file I used this code.

$(document).ready(function(){
$("#affectStudents").on('submit', function(e){
    e.preventDefault();
    var url     = $(this).attr('action');
    var data    = $(this).serialize();

    $.post(url, data, function(response) {
        if(response == 'good'){
            $("#affectedSuccessfully").show();
        }else{
            $("#affectedError").show();
        }           
    });                
});
});

When I Click the button SEND It redirect me to /etudiants/affectation even if I'm using the preventDefault(); and send no data to database.

Have you loaded JS file well? Also jQuery library? It seems to be not done, your JS function. Check also errors in debug bar, if there are some.

Edit (after discussion) :

http://jsfiddle.net/wvwm5Luz/2/ Your jQuery serialize method make each checkbox as one variable. In my opinion you can do this:

Use checkboxes without names. Get checked checkboxes (it is easy in dataTable plugin, http://datatables.net/forums/discussion/2511/get-all-checked-checkboxes-in-the-datatable should help) and add it to var data in your post . Values could be in format like '1,3,8' etc. and in etudiants_model.php write something like:

$students = explode(',', $_POST['id_etudiants'];

After that I suppose it will work.

I believe you are loading the javascript before the form is created, therefore the event handler runs before the affected element is created and as a result it does not affect the target element. You need to either register the handler after the page has been loaded

$(function() {
    $("#affectStudents").on('submit', function(e){
        e.preventDefault();
        var url     = $(this).attr('action');
        var data    = $(this).serialize();

        $.post(url, data, function(response) {
            if(response == 'good'){
                $("#affectedSuccessfully").show();
            }else{
                $("#affectedError").show();
            }           
        }                 
    });
});

or, you can write a code which will expect the target to exist in the future

$("body").on('submit', "#affectStudents", function(e){
    e.preventDefault();
    var url     = $(this).attr('action');
    var data    = $(this).serialize();

    $.post(url, data, function(response) {
        if(response == 'good'){
            $("#affectedSuccessfully").show();
        }else{
            $("#affectedError").show();
        }           
    }                 
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM