0

I have a form where I have countries list in checkbox format to be inserted into database. Say for example:

<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>

I want to insert this into database using ajax. I could have easily done this through normal same page PHP post. But when sending data with ajax to other page for processing I am confused on how to send. Once it sends all the selected checkbox values perfectly then all the rest is onto me.

My AJAX script

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

I have put a check on the processing page where if the country value is empty return error like:

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

No matter if I select one or all countries still I get this error response back. What should I do to send these checkbox data with ajax?

  • You probably are needing to use `$("input[name=country").val()` not `$("input[name=country").data("value")`. `.data()` assumes there is a `data` attribute, in this case `data-value="something"` which you don't have. You may want to just `.serialize()` the form instead, that is much more straight forward. – Rasclatt Jun 13 '17 at 15:33
  • 1
    What is the reason you can't use normal form submitting? The way you are trying can't work because `name='country[]' != name='country'` – Lixus Jun 13 '17 at 15:35
  • @Lixus also said what I was going to say, you probably need to send `"input[name=country\\[\\]]"` – Rasclatt Jun 13 '17 at 15:37
  • I got one answer by sbczk on this link https://stackoverflow.com/questions/9493531/send-multiple-checkbox-data-to-php-via-jquery-ajax and I guess this will work.. seems like it.. however how to implement it in my code is giving me a problem as I am not so good with ajax... can somone view this answer and help me implement it in my ajax code? –  Jun 13 '17 at 15:41
  • That answer assumes you don't have other checkboxes in your form named something else otherwise it will include those as part of the `country[]` checkboxes. If these are the only checkboxes then that answer will work fine. – Rasclatt Jun 13 '17 at 15:44
  • there are about 240 country names in the list with `name="country[]"` in all of them. no other name value used. @Rasclatt how can I implement that code in my code? I am getting confused... –  Jun 13 '17 at 15:48
  • You also have one too many `});` I think (syntax error). – Rasclatt Jun 13 '17 at 15:55
  • no syntax error.. all ok.. –  Jun 13 '17 at 15:56

2 Answers2

0

You will want to switch your .data() to .val() on your input capture. Also change the name of the inputs to 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>');
            }
        }
    });
});
Rasclatt
  • 12,498
  • 3
  • 25
  • 33
0

Try

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

then post it to ajax data: countries or change the code to send only checked elements

Your PHP will receive an array so you can check

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