AJAX checkboxes with Jquery and PHP

前端 未结 3 1295
伪装坚强ぢ
伪装坚强ぢ 2021-01-15 16:17

I have two rows of check-boxes. When a user clicks on any individual check-box (in a certain row) I want to add a number to my sum in PHP. If he deselects an individual chec

3条回答
  •  伪装坚强ぢ
    2021-01-15 16:58

    You have to serialize the form into a JS object, that's what goes into the data field. Here's a simple serialize function, that could be improved, but will give you an idea

    function serializeForm(form) {
        var obj = {};
        for (var i = 0; i < form.elements.length; i++) {
            var el = form.elements[i];
            if (el.name) {
                if (obj[el.name] && obj[el.name].constructor == Array ) {
                   obj[el.name].push(el.value);              
                } else if (obj[el.name]) {
                   obj[el.name] = [obj[el.name], el.value];
                } else {
                   obj[el.name] = el.value;
                }
            }
        }
        return obj; 
    }
    

    There is a plugin that lets you submit forms with AJAX easily http://jquery.malsup.com/form/ See jQuery AJAX submit form

    Assuming the following HTML

    You can just do the following to have the form posted with AJAX

    // attach handler to form's submit event 
    $('#myForm').submit(function() { 
        // submit the form 
        $(this).ajaxSubmit(); 
        // return false to prevent normal browser submit and page navigation 
        return false; 
    });
    

提交回复
热议问题