I want to pick up multiple checkbox with item ids for AJAX in select all

Asked

Viewed 146 times

2

I have a checkbox to select everything.

Underneath it I have two checkboxes.

The select all I haven’t done yet but it’s not the problem, I need only that by clicking the button, send the post with all selected checkbox!

AJAX Upload Button Code:

<button onclick="checkbox_items_select_all_javascript();">enviar selecionados</button>

The button will capture by Javascript which items below (checkbox) are selected, and send as post to the PHP file (AJAX)

I tried the code of this topic and I couldn’t make it work!

https://stackoverflow.com/questions/9493531/send-multiple-checkbox-data-to-php-via-jquery-ajax#

My two checkbox (example item 1 and item 2)

<input type='checkbox' name='checkbox_items[]' id='select_{$anuncio['id']}' value='{$anuncio['id']}' >
<input type='checkbox' name='checkbox_items[]' id='select_{$anuncio['id']}' value='{$anuncio['id']}' >

My ajax:

function checkbox_items_select_all_javascript() {
    var checkbox_items = new Array();
    $("input:checked").each(function() {
       checkbox_items = data['checkbox_items[]'].push($(this).val());
    });

  var dataString = 'checkbox_items='+ checkbox_items;
    $.ajax({
      type: "POST",
      url: "aj/checkbox_items_select_all_ajax.php",
      data: dataString,
      cache: false,
      success: function(result){
       alert(result);
      }
    });
    return false;
}

Javascript error (console):

Uncaught Referenceerror: data is not defined At htmlinputelement. (checkbox_items_select_all_javascript.js:4) At Function.each (jquery-2.1.3.min.js:2) at n.fn.init.each (jquery-2.1.3.min.js:2) checkbox_items_select_all_javascript (checkbox_items_select_all_javascript.js:3) At Htmlinputelement.onclick ((index):1) mais_opcoes.css:1 Failed to load Resource: the server responded with a status of 404 ()

1 answer

3

That one data['checkbox_items[]'] does not exist. You should do the .push() in the checkbox_items which is an array.

You do not need to use array in this case name. They don’t really need name the checkboxes (maybe not even id), suffice:

<input type='checkbox' id='select_{$anuncio['id']}' value='{$anuncio['id']}' >
<input type='checkbox' id='select_{$anuncio['id']}' value='{$anuncio['id']}' >

And in function you will do:

var checkbox_items = new Array();
$("input:checked").each(function() {
   checkbox_items.push($(this).val());
});

Will add each value of each checkbox checked in the array checkbox_items.

The result in PHP ($_POST['checkbox_items']) will be a string with values separated by a comma, something like:

"valor1,valor2"

Which you can convert into array with explode():

explode(",", $_POST['checkbox_items']);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.