Как получить доступ к массиву снаружи, если?Я использую AJAX - PullRequest
0 голосов
/ 17 мая 2019

Я отправляю данные через ajax (1, 2, 3, 4) и пытаюсь записать их в массив pColors.Проблема в том, что я не могу получить доступ к массиву.Я провел тесты и подтвердил, что данные поступают в $ _POST, но не записываются в массив.

$x = $getProductID;
$_SESSION['pColors'] = array();

if(isset($_POST['pColors'])) {  

   foreach($_POST['pColors'] as $colorKey => $RColors) {

      $_SESSION['pColors'][$x][$colorKey] = $RColors;   

    }
}

$ x получаем идентификатор продукта. Я использую их для ключа

Любые идеи о том, что этосвязано с?Спасибо!

                $('.addToCart').click(function(){
                    $.ajax({
                        url:""+realLink+"cart.php",
                        method:"POST",
                        data:{pColors:pColors},
                            success:function(data){
                               //alert(pColors);
                               //console.log(this.data);
                            }
                    });
                });

1 Ответ

1 голос
/ 17 мая 2019

Так что не уверен, что я раньше этого не видел, но ваша переменная javascript для pColors определена вне функции, вызывающей ajax, там вы отправляете пустые данные.

Я изменил ваш скрипт следующим образом:

<script>
filter_data();

function filter_data() {

    var action = 'fetch_data';


    $('.addToCart').click(function(){

        var pColors = document.getElementById("pColors").value
        $.ajax({
            url:"http://samplesite/devsite/ajax.php",
            method:"POST",
            data:{ pColors : pColors },
                success:function(data){
                console.log(data);
}
        });
    });

}
    </script>

Протестировано на моем сервере разработки и выдает следующее:

Array
(
    [pColors] => 1,2,3,4
)

Edit:

Также необходимо изменить php-файл ajax на следующий:

<code>$x = $getProductID;
$_SESSION['pColors'] = array();



    if(isset($_POST['pColors'])) {  
        foreach($_POST as $colorKey => $value) {
            if ($colorKey == 'pColors') { 


            $_SESSION['pColors'][$colorKey] = $value;
        }
        }

    }

    echo '<pre>';
    print_r($_SESSION['pColors']);
    echo '
';

Вы заметите, что foreach теперь работает на самом методе $ _POST с оператором if, чтобы затем проверить, что это правильный ключ.

Я сейчас добавил:

$colorFolder = "Placeholder Folder";

$getColorTitle = array("uniqueID" => "2");

$rowColors = array("image" => "Placeholder Image");


echo '
                                  <li>
                                  <input type="hidden" class="getColorID" id="'.$getColorTitle['uniqueID'].'" />
                                  <input type="checkbox" name="pColors" class="css-checkbox pColor" value="'.$getColorTitle['uniqueID'].'" id="cb-'.$getColorTitle['uniqueID'].'"/>
                                    <label for="cb-'.$getColorTitle['uniqueID'].'"><img src="'.$colorFolder.''.$rowColors['image'].'" height="50px" />
                                <div class="colorsC">
                                <input type="hidden" value="0" style="width: 45px;" class="qtyC" />
                                    <input type="button" value="0" style="width: 45px;" class="qtyC addToCart" />
                                </div>
                                    </label>
                                  </li>';

                                  ?>

который выводит:

<code>test.php:117 <pre>Array
(
    [] => Array
        (
            [pColors] => Array
                (
                    [0] => 2
                )

        )

)

Какой правильный ID

--- cart.php ----

<code><?php


$_SESSION['pID'] = "9";

$_SESSION['pQua'] = "20";


if(isset($_SESSION['pID']) && isset($_SESSION['pQua'])) {
    foreach($_SESSION as $getProductID => $valueTwo) {
        if ($getProductID == "pID")   {
        $x = $getProductID;
        $_SESSION['pColors'] = array();

if(isset($_POST['pColors'])) {
    foreach($_POST as $colorKey => $value) {
        if ($colorKey == 'pColors') { 
            $_SESSION['pColors'][$x][$colorKey] = $value;
        }
    }
}

    }
}
}

            echo '<pre>';
            print_r($_SESSION['pColors']);
            echo '
'; ?>

- product.php ---

<?php

include_once 'header.php';

$colorFolder = "Placeholder Folder";

$getColorTitle = array("uniqueID" => "2");

$rowColors = array("image" => "Placeholder Image");


echo '
                                  <li>
                                  <input type="hidden" class="getColorID" id="'.$getColorTitle['uniqueID'].'" />
                                  <input type="checkbox" name="pColors" class="css-checkbox pColor" value="'.$getColorTitle['uniqueID'].'" id="cb-'.$getColorTitle['uniqueID'].'"/>
                                    <label for="cb-'.$getColorTitle['uniqueID'].'"><img src="'.$colorFolder.''.$rowColors['image'].'" height="50px" />
                                <div class="colorsC">
                                <input type="hidden" value="0" style="width: 45px;" class="qtyC" />
                                    <input type="button" value="0" style="width: 45px;" class="qtyC addToCart" />
                                </div>
                                    </label>
                                  </li>';

                                  ?>

--- ajaxCart.js ---

<script>filter_data();

function filter_data() {

    $('.addToCart').click(function(){

        var pColors = get_filter('pColor');

        $.ajax({
            url:"http://samplesite/devsite/ajax2.php",
            method:"POST",
            data:{ pColors : pColors },
                success:function(data){
                   //alert(pColors);
                   console.log(data);
                }
        });
    });

}

function get_filter(class_name) {
    var filter = [];
    $('.'+class_name+':checked').each(function(){
        filter.push($(this).val());
    });

    if($('.'+class_name+'').is(':checked')){
        $('.colorsC').find('input:hidden').each(function() {
           $("<input type='text' />").attr({ style: 'width: 45px;', value: this.value }).insertBefore(this);
        }).remove();                    
    } else {
        $('.colorsC').find('input:text').each(function() {
           $("<input type='hidden' />").attr({ style: 'width: 45px;', value: '0' }).insertBefore(this);
        }).remove();
    }

    return filter;
}

$('.css-checkbox').click(function(){
    filter_data();
   });

$('.addToCart').click(function(e) {
    e.preventDefault();

    productID = $(this).attr('id');
    productQuantity = $('#productID'+productID+'').val();

    $.post('http://samplesite/devsite/ajaxAddProduct.php', {
        pID: productID,
        pQua: productQuantity,
    }, function(response){
        $('#successID'+productID+'').show('slow');
    });
    alert('Успешно добавихте продукта в количката');
    setTimeout(function() {
        $('#successID'+productID+'').hide('slow');

    }, 1000);

    return false;
});

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