简体   繁体   中英

Passing php array as a link param to an ajax function

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM