doumu1873 2017-04-26 14:28
浏览 52

将JS数组打印到div并在推送数组时刷新div

Rather new to JavaScript here, so possible silly mistakes that I haven't spotted:

The products page on my website has a search bar that pulls out products from the SQL database and then uses a standard for loop to print them out in a table, on the end of each row is an "Add to order" button that should take row item 0 ($row[0]) and insert it into a JavaScript array.

The JS array should auto refresh in the "p id='refresh_div'" it is displayed in. it should print out the product code just 'added to the order'. Currently it remains empty.

Simultaneously the array of product codes selected need to be in a PHP array also to be used by the 'mail()' function of php. However this is not yet implemented.

Basically: the 'add to order' button creates a shopping list inside a div that then gets emailed once the user presses send.

Here is my current attempt (this is inclusive of most of the page):

  <div class="container">
  <!-- Example row of columns -->
    <div class="row">
        <div class="col-md-8">
        <?php 
        $conn = connectToDatabase();
        $conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
        $conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

        ?>

        <script> // define empty array for product numbers
            var order_numbers = [];
        </script>

        <?php

        if ($_SESSION == True) {
            $current_user = $_SESSION['username'];
        } else {
            $current_user = "";
        }

        if (isset($_POST['keywords'])) {
            $keywords = $_POST['keywords'];                    
            $stmt = $conn->prepare("SELECT code, description, price, quantity FROM products WHERE description like :keywords");
            $like_keywords = '%'.$keywords.'%';
            $stmt->bindParam(':keywords', $like_keywords, PDO::PARAM_STR);
            $stmt->execute();
            $result = $stmt->fetchAll();

            if($keywords == ""){ 
                echo "Please use the search bar on the right";
                $conn = null; // close db connection 
                $result = array();   
            }
        } //endif
          // check to see if a result was returned
        if( !isset($result) ){
            echo "Please use the search bar on the right";
            $conn = null; // close db connection        
        }else{
            if( isset($_SESSION['discount']) ) {
                $mydiscount = $_SESSION['discount'];
                }else{
                    $mydiscount = 1;
                }

                $out = "<table class='table table-hover'>";
                $out .= "<tr>";
                $out .= "<th><p>Product Code</p></th>";
                $out .= "<th><p>Description</p></th>";
                $out .= "<th><p>Price</p></th>";
                $out .= "<th><p>Stock</p></th>";
                $out .= "<th></th>";
                $out .= "</tr>";


                foreach ($result as $row) {
                    $out .= "<tr>";
                    $out .= "<td><p>".$row[0]."</p></td>";
                    $out .= "<td><p>".$row[1]."</p></td>";

                    $userprice = $mydiscount * $row[2];
                    $userprice = number_format($userprice,2);

                    $out .= "<td><p>£".$userprice."</p></td>";
                    $out .= "<td><p>".$row[3]."</p></td>";
                    $out .= "<td><button class='btn btn-success' id='refresh_button' onclick='var row_code = <?php echo json_encode($row[0]); ?>; order_numbers.push(row_code);'>Add to order</button></td>";//ON BUTTON CLICK put $row[0] into row_code and push row_code onto order_numbers array 
                    $out .= "</tr>";
                }// end foreach

                $out .= "</table>";

                echo $out;

            }// end else
            ?>
        </div>

        <div class="col-md-4">
            <form action="" method="post">
                <input name='keywords' type='text' placeholder='Search Products' class='form-control' autofocus>
                <button type='submit' class='btn btn-success'>Search</button>
            </form >

            <hr>

            <script>

            $(function() {
                $("#refresh_button").on("click", function() {
                    $("#refresh_div").load("#refresh_div")
                    return false;// ON SAME BUTTON CLICK refresh the id that contains print array
                })
            })

            order_numbers.toString();//convert to string
            document.getElementById('refresh_div').innerHTML = order_numbers;//print
            </script>

            <p id='refresh_div'></p>//in this id



            <?php //EVERYTHING BELOW HERE IS UNRELATED (i have not yet converted the JS array back into the PHP array for mailing ($order_numbers)



            $to = 'sample@email.com';
            $subject = 'WEB ORDER from '.$current_user;
            $contact_submitted = 'Thank you for your order, one of our staff will contact you to confirm.';

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

                if ($_SESSION == true && isset($order_numbers) && substr(md5($user_answer),5,10) === $answer) {
                    mail($to,$subject,$order_numbers);

                    echo '<p>'.$contact_submitted.'</p>';

                }
                else echo '<p>You must be logged in, have added items to your order and have answered the simple maths question before submitting your order.</p>';
            }
            $number_1 = rand(1, 9);
            $number_2 = rand(1, 9);
            $answer = substr(md5($number_1+$number_2),5,10);
            ?>
            <form id="contact" action="products.php" method="post">
                <div class="form_settings">
                    <p style="line-height: 1.7em;">
                        To help prevent spam, please enter the answer to this question:
                    </p>
                    <p>
                    <span>
                        <?php echo $number_1; ?> + <?php echo $number_2; ?> = ?
                    </span>
                    <br>
                    <input class="form-control" type="text" name="user_answer" />
                    <input type="hidden" name="answer" value="<?php echo $answer; ?>" />
                    <input class="btn btn-success" type="submit" name="contact_submitted" value="send" />
                </div>
            </form>
        </div>
    </div>

Any advice would be greatly appreciated, again apologies for any glaring mistakes.

Thanks in advance.

EDIT: apologies I can't comment as this is my first ever post and I don't have the rating.

I should be more specific, if there are errors it would be great if anyone could point them out and if you submit an answer it would be really useful if you could give a brief explanation as to why yours will work and mine didn't so I can learn from it :)

EDIT 2: updated title to clarify

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
    • ¥15 python的qt5界面
    • ¥15 无线电能传输系统MATLAB仿真问题
    • ¥50 如何用脚本实现输入法的热键设置
    • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
    • ¥30 深度学习,前后端连接
    • ¥15 孟德尔随机化结果不一致
    • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
    • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
    • ¥15 谁有desed数据集呀