P
P
Pavel2017-10-28 02:00:41
JavaScript
Pavel, 2017-10-28 02:00:41

Why isn't an ajax request sent when a checkbox is clicked?

When reading a json file, I form the data output in html. Html code is generated normally. I use the received data from json to form checkboxes (livelist_more function). When clicking on checkboxes, the request should be sent to the send function, but for some reason it is not sent.

PS
The error in my opinion is that the function does not see the function. Tried different options, but without success.
Please help me figure out what is wrong and, if possible, an example.

//data sending function

function send(data){
     $.ajax({
            type: "get",
            url: url_send,
            data: data,
            cache: false,
            success: function(html){
               $('#result2').append(data+'<br>');
            }
        });
        return false;

  }

json file
[{"id": 15, "name": "\u0422\u0435\u0441\u0442\u043e\u0432\u044b\u0439 livelist 2", "rotations": [3, 5]},
{"id" : 18, "name": "\u041d\u043e\u0432\u044b\u0439 livelist", "rotations": []}]

//sending values ​​with ajax to checkbox send function
$(document).ready(function(){
 $('input[type="checkbox"]').each(function () {
        $(this).change(function(){
          if($(this).attr("checked")){
            send($(this).attr("name")+'='+1);
            }else{
              send($(this).attr("name")+'='+0);
              }
              });
              });


//функция для разбора json и формирования html кода

function livelist_more (){
$.getJSON(file.json, function(data) {
  var items = [];
 $.each(data, function(key,val) {
items.push('<li><label>' + val.name + '(' + val.id + ') <input type="checkbox" name="ch_' + val.id + '" id="ch_' + val.id + '"  /></li>');

});
 $('<ul/>', {
   'class': 'my-new-list',
   html: items.join('')
 }).appendTo('#livelist_el');
});


};

livelist_more ();
} );

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Burov, 2017-10-28
@pzpzpz

$('input[type="checkbox"]').each(function () {
Processes only currently existing checkboxes

$('#livelist_el').on('change', 'input[type="checkbox"]', function(){
  if($(this).attr("checked")){
    send($(this).attr("name") + '=' + 1);
  } else {
    send($(this).attr("name") + '=' + 0);
  }
})

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question