使用json在db上插入多个复选框

时间:2016-10-05 04:47:56

标签: php jquery mysql json ajax

我正在使用表单验证插件,在我的js文件中,我将此输入和复选框值传递给json

$('form').submit(function(event) {

    $('.form-group').removeClass('has-error'); // remove the error class
    $('.help-block').remove(); // remove the error text
    var chkbox = new Array();
    $('input:checked').each(function() {
        chkbox.push(parseint($(this).val()));
    });

    var formData = {
        'company_name': $('input[name=company_name]').val(),
    }

    $.ajax({
        type: 'POST', // define the type of HTTP verb we want to use (POST for our form)
        url: 'process.php',
        data: formData,chbox,
        dataType: 'json',
        encode: true
    }).done(function(data) {
        console.log(data); 
        if ( ! data.success) {
            if (data.errors.company_name) {
                $('#company_name-group').addClass('has-error');
                $('#company_name-group').append('<div class="help-block">' + data.errors.company_name + '</div>');

然后在php

$errors         = array(); 
$data           = array(); 

                if (empty($_POST['company_name']))
                    $errors['company_name'] = 'Company Name is required.';
                if ( ! empty($errors)) {
                    // if there are items in our errors array, return those errors
                    $data['success'] = false;
                    $data['errors']  = $errors;
                } else {
                    $company_name=mysqli_real_escape_string($con,$_POST['company_name']);
                    $chkbox = $_POST['chkbox'];
                    $chkNew = "";  
                foreach($chkbox as $chkNew1)  
                {
                    $chkNew .= $chkNew1 . ",";  
                }  

                $ins_query="insert into xxx(`company_name`,`Job`)values('company_name','$chkNew');"
                retval = mysqli_query( $con ,  $ins_query);
                $data['success'] = true;
                $data['message'] = 'Success!';
            }
            echo json_encode($data);

这项工作完全适用于db值的表单插入值,但它在我的process.php文件中停止并且不显示页面上的消息。当我从js文件表单中删除chkbox时验证并在成功插入时显示消息成功db。

1 个答案:

答案 0 :(得分:1)

$chkNew中的最后一个字符是,

你应该删除它。

尝试在foreach之后添加此内容:

$chkNew= trim($chkNew, ',');