如何通过PHP MVC使用ajax jquery post发送checkbox数组和其他一些值

时间:2021-12-11 13:41:54

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

我正在尝试使用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:

对于View文件;我试图发送这样的数据:

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.

对于JS文件,我使用了这段代码。

$(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.

当我单击按钮SEND它将我重定向到/ etudiants / affectation即使我正在使用preventDefault();并且不向数据库发送数据。

2 个解决方案

#1


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

我相信您在创建表单之前加载了javascript,因此事件处理程序在创建受影响的元素之前运行,因此它不会影响目标元素。您需要在页面加载后注册处理程序

$(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();
        }           
    }                 
});

#2


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.

你有没有加载JS文件?还有jQuery库?似乎没有完成,你的JS功能。检查调试栏中的错误,如果有的话。

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:

http://jsfiddle.net/wvwm5Luz/2/您的jQuery序列化方法将每个复选框作为一个变量。在我看来,你可以这样做:

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:

使用没有名称的复选框。获取选中的复选框(在dataTable插件中很容易,http://datatables.net/forums/discussion/2511/get-all-checked-checkboxes-in-the-datatable应该有帮助)并将其添加到帖子中的var数据。值可以是'1,3,8'等格式,在etudiants_model.php中可以写如下:

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

After that I suppose it will work.

在那之后,我想它会起作用。

#1


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

我相信您在创建表单之前加载了javascript,因此事件处理程序在创建受影响的元素之前运行,因此它不会影响目标元素。您需要在页面加载后注册处理程序

$(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();
        }           
    }                 
});

#2


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.

你有没有加载JS文件?还有jQuery库?似乎没有完成,你的JS功能。检查调试栏中的错误,如果有的话。

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:

http://jsfiddle.net/wvwm5Luz/2/您的jQuery序列化方法将每个复选框作为一个变量。在我看来,你可以这样做:

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:

使用没有名称的复选框。获取选中的复选框(在dataTable插件中很容易,http://datatables.net/forums/discussion/2511/get-all-checked-checkboxes-in-the-datatable应该有帮助)并将其添加到帖子中的var数据。值可以是'1,3,8'等格式,在etudiants_model.php中可以写如下:

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

After that I suppose it will work.

在那之后,我想它会起作用。