Как передать значение внутри JS - PullRequest
0 голосов
/ 11 апреля 2019

У меня есть это NULL VALUE ON $_SESSION внутри моего compare.php. Вы знаете, как это исправить?

Спасибо

Функция js:

$(function() {
    $('input[type=checkbox]').change(function() {   
        var chkArray = [];   
        $('#container').html('');

        //put the selected checkboxes values in chkArray[]
        $('input[type=checkbox]:checked').each(function() {
            chkArray.push($(this).val());
        });


        //If chkArray is not empty show the <div> and create the list
        if(chkArray.length !== 0) {
            $('#container').show();           
            $.each(chkArray, function(i, val) { 
                $('<p>').text(chkArray[i]).appendTo('#container');
            });


            $('#rectButton').on('click', function (e) {     
             $.ajax({
                method: 'POST',
                url : "http://localhost/shop/ext/ajax/products_compare/compare.php",
                data : {product_id:chkArray},
/*
                success : function(resp){
                    alert("Product is added to be compared" );
                }
*/                
             });
           });

        }else{
            $('#container').hide();   
            $('#container').html('');
        }
    });    
})             
</script>

<button id="rectButton" class="btn"><a href="compare.php">Compare</a></button> 

мой ajax-файл

 $product_id = $_POST['product_id'];

 if(!is_array($_SESSION['ids'])) {
   $_SESSION['ids'] = [];
 } else {
   array_push($_SESSION['ids'], $product_id);
 }

результат ajax-файла:

product_id[]: 12
product_id[]: 10
product_id[]: 9

мой файл сравнить файл .php с результатом ajax.

var_dump($_SESSION] ===> NULL
var_dump($_SESSION]N['ids']; ===> NULL


result I see:
array(1) { ["ids"]=> array(5) { [0]=> array(1) { [0]=> string(2) "10" } [1]=> array(2) { [0]=> string(2) "10" [1]=> string(1) "9" } [2]=> array(1) { [0]=> string(1) "9" } [3]=> array(2) { [0]=> string(2) "12" [1]=> string(1) "9" } [4]=> array(3) { [0]=> string(2) "12" [1]=> string(2) "11" [2]=> string(1) "9" } } }

хорошорезультат будет иметь:

[4]=> array(3) { [0]=> string(2) "12" [1]=> string(2) "11" [2]=> string(1) "9" } 

1 Ответ

0 голосов
/ 12 апреля 2019

Поскольку $_POST['product_id'] - это массив, вы не должны помещать весь массив в переменную сеанса как один элемент, поэтому вы получаете двумерный массив. Вам следует просто назначить новый массив переменной сеанса, поскольку он содержит все элементы, которые пользователь проверил.

$_SESSION['ids'] = $_POST['product_id'];

Вы не должны связывать обработчик щелчков внутри обработчика изменений. Вы должны связать два обработчика независимо, и они оба могут использовать глобальную переменную chkArray.

$(function() {
  var chkArray = [];
  $('input[type=checkbox]').change(function() {
    $('#container').html('');

    //put the selected checkboxes values in chkArray[]
    chkArray = $('input[type=checkbox]:checked').map(function() {
      return this.value;
    }).get();

    //If chkArray is not empty show the <div> and create the list
    if (chkArray.length !== 0) {
      $('#container').show().html('');
      $.each(chkArray, function(i, val) {
        $('<p>').text(chkArray[i]).appendTo('#container');
      });
    } else {
      $('#container').hide().html('');
    }
  });

  $('#rectButton').on('click', function(e) {
    $.ajax({
      method: 'POST',
      url: "//localhost/shop/ext/ajax/products_compare/compare.php",
      data: {
        product_id: chkArray
      },
      /*
      success: function(resp) {
        alert("Product is added to be compared");
      }
      */
    });
  });

})
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...