0

i'm trying to pass a php array to an ajax function, because i need the ajax function to populate some dynamically created tables. so in order to do this i figured that i have to pass the values i intend to pass in an array, and pass them all at once, so that my ajax function can declare just once, to avoid the problem where the last dynamic table is only populated at the end(though i'm not too sure if that's the reason why). And also how to $_GET the array params that i'll be sending,but so far the result is the reverse, because it's the first dynamic table that populates. so that makes me believe that only the first array value is being send by my ajax. Heres my code:

<script>
function cat_product(val1){
    if(window.XMLHttpRequest){
        xhttp = new XMLHttpRequest();
    }else{
        xhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xhttp.onreadystatechange = function(){
        if(xhttp.readyState == 4 && xhttp.status == 200){
            window.alert(val1.length);//this proves to me that the ajax works
            document.getElementById("cat_products").innerHTML = xhttp.responseText;
        }
    };

    xhttp.open("POST","ajax/cat_product.php?id="+val1,true);
    xhttp.send();
}

</script>

    <?php
    $store_key = $_SESSION['store_key'];   
        $query = "SELECT category_key FROM product_category WHERE store_key = '{$store_key}' ORDER BY category_name ASC";
        $category_set = mysqli_query($connect,$query);//for loop
        confirm_query($connect,$category_set);
        $number = mysqli_num_rows($category_set);

      $_SESSION['sesssion_category'] = array();
      $_SESSION['sesssion_productCategory'] = array();
       $_SESSION['value'] = array();
      for($i=0;$i<$number;$i++){
     $sessionCategory = mysqli_fetch_array($category_set);

      $_SESSION['sesssion_category'][] = $sessionCategory['category_key'];
        }



     foreach ($_SESSION['sesssion_category'] as $value) {

    $_SESSION['value'][] = $value; // this is the array where i store the values i want to pass
     /* this where i create another array who's key are named after each values
from $_SESSION['sesssion_category'] and allocate items that matches each key  from the database */
    if($_SESSION['store_key'] == $_SESSION['user_id']){
       $query = "SELECT DISTINCT product_key FROM products WHERE store_key = '{$store_key}' AND category_key = '{$value}' ORDER BY branch_code,product_name ASC";
      $product_set = mysqli_query($connect,$query);
     confirm_query($connect,$product_set);
     while($product = mysqli_fetch_array($product_set)){
     $_SESSION['sesssion_productCategory'][$value][] =  $product['product_key'];
        }

    }else{
     $query = "SELECT DISTINCT product_key FROM products WHERE store_key = '{$store_key}' AND branch_code = '{$_SESSION['branch_code']}' AND category_key = '{$value}' ORDER BY branch_code,product_name ASC";
     $product_set = mysqli_query($connect,$query);
     confirm_query($connect,$product_set);
     while($product = mysqli_fetch_array($product_set)){
     $_SESSION['sesssion_productCategory'][$value][] =  $product['product_key'];
        }

    }



    ?>
    <ol id="chaps">
    <li><button class="button button-3d button-leaf" ><?php echo ucfirst(get_category($value));?></button>

    <table id="datatable1" class="table table-striped table-bordered assignments hide" cellspacing="0" width="100%">
    <caption>Product Details</caption>
    <thead>
     <tr>
       <th>#</th>
       <th>Product Name</th>
       <th>Total Pieces</th>
       <?php 
       if($_SESSION['store_key'] == $_SESSION['user_id']){
       echo "<th>Action</th>";  
       }else{
        echo ""; 
        }
        ?>
      </tr>
    </thead>

      <tfoot>
    <tr>
     <th>#</th>
     <th>Product Name</th>
     <th>Total Pieces</th>
       <?php 
     if($_SESSION['store_key'] == $_SESSION['user_id']){
      echo "<th>Action</th>";  
     }else{
       echo ""; 
      }
       ?>
    </tr>
    </tfoot>
    <tbody id="cat_products">

    </tbody>
    </table>


      </li>
    </ol>

    <?php
    }

    ?>
    </div>   


    </div>

    </div>




<!--<script>
var x = <?php echo '["' . implode('", "', $_SESSION['value']) . '"]' ?>;
window.onload = cat_product.apply(this,x);
</script>-->
<script>
var x = <?php echo json_encode($_SESSION['value']) ?>;
window.onload = cat_product.apply(this,x);
</script>

i tried the (<?php echo '["' . implode('", "', $_SESSION['value']) . '"]' ?>;`) but it's like it's not reliable.

then the ajax page where i process my ajax cat_product.php

    $value = $_GET['id'];//$value = explode(",", $_GET["id"]);


    foreach($_SESSION['value'] as $sessionValue){

    if($sessionValue == $value){
    //create an array of $_SESSION['sesssion_productCategory'] category keys
     $ary = array_keys($_SESSION['sesssion_productCategory']);
    foreach($ary as $cat_key){
    //Count the created array inorder not to exceed number of products
    for($j=0;$j<count($ary);$j++){
    //query for displaying products
    if($sessionValue == $cat_key){
    $value2 = $sessionValue;
foreach($_SESSION['sesssion_productCategory'][$value2] as $key){
    ?>
    <tr>
    </tr>    
    <?php
                                         }
                                    }
                                }
                            }
                        }
                    }
        ?>
Ikechukwu
  • 1,135
  • 1
  • 13
  • 30
  • you could pass your php array as json in a – DTH Oct 12 '16 at 13:13
  • i'm still a novice at javascript, not sure i understand "So you could construct your javascript serverside using php." that you said,except you mean process javascript in code, in a way it runs smoothly with php? – Ikechukwu Oct 12 '16 at 13:18
  • Try looking at this post's answer http://stackoverflow.com/questions/4885737/pass-a-php-array-to-a-javascript-function – DTH Oct 12 '16 at 13:19

1 Answers1

2

Try encoding your array as JSON and sending the object in the parameters.

var myArray = ["one", "two", "three"];

sendarray = JSON.stringify(myArray);

xhttp.send("myArray="+encodeURIComponent(sendarray));

On your page that parses the POST data, call the json_decode() function on $_REQUEST['myArray'].

This can also be used to post javascript objects to a php page. Good luck.

Joeseppi
  • 58
  • 6
  • i'll try this out now – Ikechukwu Oct 12 '16 at 13:30
  • Your foreach loop is not storing your variables as you are requiring. Declare the array outside of the for loop and then push the values to the array in the loop. e.g $_SESSION['values'] = array(); And then in the foreach loop do: array_push($_SESSION['values'], $value); But if you are storing the results from the DB in the SESSION then why do you need to POST them in an array? You should be able to access SESSION data from the AJAX page? Make sure to put session_start(); at the beginning of each page. – Joeseppi Oct 12 '16 at 13:49