php - How to access an array outside if? I use ajax

201

I send data via ajax (1, 2, 3, 4) and try to write them in the 'pColors' array. The problem is I can not access the array. I did the tests and confirmed that the data arrives at $ _POST but not recorded in the array.

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

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

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

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

    }
}

$x get product id I use them for key

Any ideas on what this is due to? Тhanks !

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

Answer

Solution:

So not sure how I didn't see this sooner, but your javascript variable for pColors is defined outside the function calling the ajax, there you are sending empty data.

I modified your script to the following:

<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>

Tested on my development server and it outputs the following:

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

Edit:

Also needed to change the ajax php file to the following:

$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 '</pre>';

You'll notice the foreach is now running on the $_POST method itself with an if statement to then check it's the correct key.

I've now added:

$colorFolder = "Placeholder Folder";

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

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


echo '
                 <li>
                 <input type="hidden" id="'.$getColorTitle['uniqueID'].'" />
                 <input type="checkbox" name="pColors" value="'.$getColorTitle['uniqueID'].'" id="cb-'.$getColorTitle['uniqueID'].'"/>
                  <label for="cb-'.$getColorTitle['uniqueID'].'"><img src="'.$colorFolder.''.$rowColors['image'].'" height="50px" />
                <div >
                <input type="hidden" value="0"  />
                  <input type="button" value="0"  />
                </div>
                  </label>
                 </li>';

                 ?>

which outputs:

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

        )

)
</pre>

Which is the correct ID

--- cart.php ----

<?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 '</pre>';


?>

-- product.php ---

<?php

include_once 'header.php';

$colorFolder = "Placeholder Folder";

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

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


echo '
                 <li>
                 <input type="hidden" id="'.$getColorTitle['uniqueID'].'" />
                 <input type="checkbox" name="pColors" value="'.$getColorTitle['uniqueID'].'" id="cb-'.$getColorTitle['uniqueID'].'"/>
                  <label for="cb-'.$getColorTitle['uniqueID'].'"><img src="'.$colorFolder.''.$rowColors['image'].'" height="50px" />
                <div >
                <input type="hidden" value="0"  />
                  <input type="button" value="0"  />
                </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>

People are also looking for solutions to the problem: php - Custom validation error messages in CodeIgniter config file

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.