Search code examples
javascriptphparraysjqbootstrapvalidation

Pass PHP array from Javascript


I would like to pass a PHP array from JavaScript.

PHP Data Table

---------------------------
| adminID |  adminEmail   |
===========================
|    1    | [email protected] |
|    2    | [email protected] |
===========================

Javascript

<script>
    function checkuser_callback_function($el, value, callback) {
    var $array = new Array("[email protected]","[email protected]");
    var valid = false;
    if($array.indexOf(value) == -1){
        valid = true;
    }
    callback({
        value: value,
        valid: valid,
        message: "User present."
    });
}
</script>

I want to pass that adminEmail here var $array = new Array("..","..");

I have tried alot in php but I didn't get any result.

<?php
    include 'config.php';
    $sql ="SELECT adminEmail FROM BEadmin";
    $result = mysqli_query($con,$sql);

    while($row = mysqli_fetch_assoc($result)) {
        $array = $row;
        $str = "'" . implode ( "', '" ,$array ) . "'";
        $parts = split("'", $str);
        print_r($str);
    }
?>

Solution

  • You can use php to create javascript array. Then use the same in the script later. Please note that , just to differentiate, I have called javascript array jArray instead of $array. Rest is explained along in the script only. Hope this helps..

            <?php
            include 'config.php';
            $sql ="SELECT adminEmail FROM BEadmin";
            $result = mysqli_query($con,$sql);
    
            //start script tag
            echo "<script>\n";
            // javascript array decalaration beginning
            echo "var jArray = new Array(";
    
            $arrStr = "";
            while($row = mysqli_fetch_assoc($result)) {
            //                $array = $row;
            //                $str = "'" . implode ( "', '" ,$array ) . "'";
            //                $parts = split("'", $str);
            //                print_r($str);
                $arrStr .= '"'. $row["adminEmail"] . '",';
            }
    
            // drop the last , from the string
            $arrStr = substr($arrStr,0,-1);
            // now populate javascript array with this string
            echo $arrStr;
    
            // end javascript array
            echo ");\n";
            echo "</script>\n";
        ?>