AJAX checkboxes with Jquery and PHP

前端 未结 3 1276
伪装坚强ぢ
伪装坚强ぢ 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:57

    Try:

    <script type="text/javascript">
     function processForm() { 
        $.ajax( {
            type: 'POST',
            url: 'submit_form.php',
            data: { checked_box : $('input:checkbox:checked').val()},
    
            success: function(data) {
                $('#message').html(data);
            }
        } );
    }
    </script>
    
    0 讨论(0)
  • 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

    <form id="myForm" action="submit_form.php" method="post"> 
      <input type="checkbox" name="standard_form[]" value="A" onclick="processForm()">
      <input type="checkbox" name="premium_form[]" value="B" onclick="processForm()">
    </form>
    

    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; 
    });
    
    0 讨论(0)
  • 2021-01-15 17:05

    In checkboxes try onclick="processForm(this)", then, in JavaScript:

    <script type="text/javascript">
    function processForm(elm) { 
            $.ajax( {
                type: 'POST',
                url: 'submit_form.php',
                data: elm.name+'='+elm.value,
    
                success: function(data) {
                    $('#message').html(data);
                }
            } );
    }
    </script>
    
    0 讨论(0)
提交回复
热议问题