使用ajax发送多个复选框数据

时间:2017-06-13 15:30:05

标签: javascript php jquery ajax checkbox

我有一个表单,其中我有国家/地区列表以复选框格式插入数据库。比如说:

<input type="checkbox" name="country[]" value="Afghanistan" checked>Afghanistan<br>
<input type="checkbox" name="country[]" value="Albania" checked>Albania<br>
<input type="checkbox" name="country[]" value="Algeria" checked>Algeria<br>
<input type="checkbox" name="country[]" value="American Samoa" checked>American Samoa<br>
<input type="checkbox" name="country[]" value="Andorra" checked>Andorra<br>
<input type="checkbox" name="country[]" value="Angola" checked>Angola<br>
<input type="checkbox" name="country[]" value="Anguilla" checked>Anguilla<br>

我想使用ajax将其插入数据库。我可以通过普通的同一页PHP帖子轻松完成此操作。但是当使用ajax将数据发送到其他页面进行处理时,我对如何发送感到困惑。一旦它完美地发送了所有选中的复选框值,那么剩下的就全部发给我了。

我的AJAX脚本

$("#submit").click(function() {
    var dataString = {
    clicks: $("#clicks option:selected").data("value"),
    country: $("input[name=country").data("value") // tried using this and input[name=country[]] but they did not work. 
    };
$.confirm({
    title: 'Confirm!',
    content: 'Are you sure you want to purchase this advertisement?',
    buttons: {
    confirm: function () {
                $.ajax({
                    type: "POST",
                    dataType : "json",
                    url: "add-ptc-process.php",
                    data: dataString,
                    cache: true,
              beforeSend: function(){
                    $("#submit").hide();
                $("#loading-rent").show();
                        $(".message").hide();
              },
                    success: function(json){
                setTimeout(function(){
                        $(".message").html(json.status).fadeIn();
                    $('#mywallet').html('$' + json.deduct);
                  $("#loading-rent").hide();
                  $("#submit").show();
                    },1000);
                    }
                });
    },
    cancel: function () {
      $.alert('<span style="font-size: 23px">Purchase Cancelled!</span>');
    }
    }
    });
    return false;
});
});

我已经检查了处理页面,如果国家/地区值为空,则返回错误,如:

if($country == ''){
    echo "No countries selected. Please select at least one country.";
}

无论我选择一个还是所有国家,我都会收到此错误回复。如何使用ajax发送这些复选框数据?

2 个答案:

答案 0 :(得分:0)

您需要在输入捕获中将.data()切换为.val()。同时将输入名称更改为input[name=country\\[\\]]:checked

# Use "e" as the event
$("#submit").click(function(e) {
    # Use this function to stop the form
    e.preventDefault();
    # You could make a quick function to save all the countries
    # You can actually feed other selectors into this as well, so
    # it can do all your value retrievals, not just for countries
    function getCountries(checkboxes)
        {
            var getVals =   [];
            $.each($(checkboxes),function(k,v) {
                getVals.push($(v).val());
            });

            return getVals; 
        }

    var dataString = {
        clicks: $("#clicks option:selected").val(),
        # Run the function to gather
        # Note the name (escaped [] with :checked)
        country: getCountries("input[name=country\\[\\]]:checked")
    };

    $.confirm({
        title: 'Confirm!',
        content: 'Are you sure you want to purchase this advertisement?',
        buttons: {
            confirm: function () {
                $.ajax({
                    type: "POST",
                    dataType: "json",
                    url: "add-ptc-process.php",
                    data: dataString,
                    cache: true,
                    beforeSend: function(){
                        $("#submit").hide();
                        $("#loading-rent").show();
                        $(".message").hide();
                    },
                    success: function(json){
                        setTimeout(function(){
                            $(".message").html(json.status).fadeIn();
                            $('#mywallet').html('$' + json.deduct);
                            $("#loading-rent").hide();
                            $("#submit").show();
                        },1000);
                    }
                });
            },
            cancel: function () {
                $.alert('<span style="font-size: 23px">Purchase Cancelled!</span>');
            }
        }
    });
});

答案 1 :(得分:0)

尝试

var countries = {};
$('input[name^="country"]').each(function(){
          countries[$(this).attr('value')] = $(this).is(":checked");
});

然后将其发布到ajax数据:国家/地区或更改代码以仅发送已检查的元素

您的PHP将收到一个数组,以便您检查

if(is_array($_POST['countries'])){
         foreach($_POST['countries'] AS $country_name => $is_checked){
                  //do something...
         }
}