Hello.

Please tell me which side to approach this problem:

There is a construction in HTML:

<input type="checkbox" name="1"> <input type="checkbox" name="2"> <input type="checkbox" name="3"> <input type="checkbox" name="4"> 

There are arrays in PHP (of course you can rename them):

 <? $id_1 = array(1,2,3); $id_2 = array(5,6,7); $id_3 = array(8,9,10); $id_4 = array(11,12,13); ?> 

using the following JS code, when you turn on any two checkboxes, a specific action is started:

 $("input[type='checkbox']").change(function(){ var checked = $("input[type='checkbox']:checked").length; if (checked == 2) { ---действие---; } }); 

How to make the action to run a separate PHP code that would use arrays corresponding to the checkbox names?

Ps Let me explain why everything is done. There is a table with a list of banks and their lending terms. In addition, arrays were created in which overpayments were recorded by months for each bank (i.e. [0] - overpayment on the loan in the first month for this bank, [1] - in the second and so on. I want to make it so that two banks through a checkbox, a window appeared in which a chart with overpayments of both banks was built through a google chart. Something like this ...

  • Using ajax, you can invoke separate php scripts. Describe the overall goal of the task, it is not very clear now why everything is done. - Vasily Koshelev
  • @Vasily Koshelev explained. - Oktu
  • I think it would be easier to make a request for ajax to the script, passing the id of the selected banks. In the php script, pull data from the database, fill it with an array and convert it to json. Accept the answer in the clear js json-e and update the schedule in accordance with this data. - Vasily Koshelev
  • Thanks @Vasily Koshelev. But pulling data from the database means drawing a lot more from the front, and the arrays are already created and ready, even in order to save time, I want to find a way with the arrays already created. Understood one thing that can not do without json. - Oktu

4 answers 4

 $("input[type='checkbox']").change(function(){ var checked = $("input[type='checkbox']:checked"); if (checked.length == 2) { var names = $.map(checked, function(ch){ return $(ch).attr('name'); }); // Далее выполняем ajax запрос к php скрипту, куда и передаём names $.ajax({ url : 'https://httpbin.org/post', method : 'post', contentType: "application/json; charset=utf-8", // data : {names: names}, автоматически выполнится $.param, будет names[]=3&names[]=4 data : JSON.stringify({names: names}), dataType: 'json', success : function(res){ var form = JSON.parse(res.data); console.log(form.names); } }); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="checkbox" name="1"> <input type="checkbox" name="2"> <input type="checkbox" name="3"> <input type="checkbox" name="4"> 

In php, you will get an array ['names'] form [1, 3] in the json request body:

 <?php // Обратите внимание, данные не в форме `$_POST`, а в теле запроса, их нужно распарсить вручную. $input = json_decode(file_get_contents('php://input'), TRUE); $names = $input['names']; // Имитируем ответ от httpbin.org, чтобы не менять js header('Content-type: application/json; charset=UTF-8'); echo json_encode(['data' => json_encode(['names' => $names])]); exit(); 

To get data in the $_POST array, you need to send an x-www-formurlencoded request:

 $("input[type='checkbox']").change(function(){ var checked = $("input[type='checkbox']:checked"); if (checked.length == 2) { var names = $.map(checked, function(ch){ return $(ch).attr('name'); }); // Далее выполняем ajax запрос к php скрипту, куда и передаём names $.ajax({ url : 'https://httpbin.org/post', method : 'post', data : {names: names}, // data : $.param({names: names}), // это выполнится автоматически success : function(res){ console.log(res.form['names[]']); } }); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="checkbox" name="1"> <input type="checkbox" name="2"> <input type="checkbox" name="3"> <input type="checkbox" name="4"> 

PHP in this case:

 <?php $names = $_POST['names']; // Имитируем ответ от httpbin.org, чтобы не менять js header('Content-type: application/json; charset=UTF-8'); echo json_encode(['form' => ['names[]' => $names]]); exit(); 
  • Your answer seems the most logical, but for some reason it does not work for me. I correctly understand that instead of httpbin.org/post I add the path to the php file in which, through $ _POST ['names'], should the logic get an array? and should this array appear without reloading this file? - Oktu
  • @Oktu, added a php script to look like, so that everything works just like httpbin.org . The fact is that php does not parse the json request body by itself. - vp_arth
  • First, thanks for helping! Secondly, I understand the question step by step: I decided to ask for it, and removed the dataType line: 'json', and after that the array became available simply through $ name = $ _POST ['names']; Can I go this way? - Oktu
  • @Oktu, dataType could not influence this. It is responsible for the expected response format from the server. Either you changed something else, or it worked initially and you checked it incorrectly. - vp_arth

Use ajax. Using jQuery.ajax, it will look something like this:

 $.ajax({ method: "POST", url: "../your_file.php", data: $('#form').serialize(), // Сериализация формы complete: function(data) { // Получаем ответ сервера }, error: function(jqXHR, textStatus) { // Если при обработке запроса возникла ошибка } }); 

In PHP, get data and process it according to your requirements.

JQuery.ajax () Documentation

    It is possible so http://codepen.io/keesik/pen/xqLorw

     $("input[type='checkbox']").change(function(){ var checked = $("input[type='checkbox']:checked"); if (checked.length > 1) { var data = []; checked.each(function(){ data.push($(this).attr('name')) }); $.ajax({ url : '/Путь к скрипту на сервере', method : 'get', // или post data : 'checked=' + data.join(','), // данные в php скрипте будут достпны в переменной $_REQUEST['checked']. Все выбранные пункты будут перечислены через запятую. success : function(res){ console.log(res); // ответ от сервера alert('Ajax request done'); } }) } }); 

      During page generation, transfer arrays to related inputs in data attributes and then drag them through js by condition.

      In the php file, combine the arrays into strings; assign these strings to the data attributes.

       somewhere in your.php ... $id1 = implode(',' , array(1,2,3)); ... ?> <input type="checkbox" name="1" data-array="<?=$id1;?>" /> ... 

       var checkTocheck = function(){ var checked = $("input:checked").attr('name'); var url, data; switch(checked){ case '1': case '2': case '3': case '4': url = "4.php" break; } data = $("input:checked").data('array').split(','); $.ajax({ url: url, data: data, success: function(data){ $('body').append(data); } }) }; checkTocheck(); $("input[type=checkbox]").on("click",checkTocheck); 
       <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="checkbox" name="1" data-array="1,2,3" /> <input type="checkbox" name="2" data-array="5,6,7" /> <input type="checkbox" name="3" data-array="8,9,10" /> <input type="checkbox" name="4" data-array="11,12,13" /> <div id="console"></div> 

      • And where is the data transfer in PHP ?? - GHosT
      • In fact, it is unclear why we should take the data of the arrays from the front (which will get from the back) to return them back to the back. It is enough to send only the name and by it to bind arrays with data on the back. - br3t