简体   繁体   中英

How do i use Javascript to “store” and “call” data?

I'm making a "Catalog" page for a fake shop site, when i click one of the thumbnails shown on the page a java-script overlay is meant to show up with all the information for the product (such as a larger image 'photo1') with that thumbnail (The products are in an SQL database).

While this does pull up an overlay as intended it doesn't get just the one related 'photo1', it instead gets all of them from the table.

I've had help from a teacher but she couldn't even help, but from what i gather i need a way to store what thumbnail was chosen so i can clarify what info to pull for the overlay.

Main:

<div id="overlay">
    <div>
    <?php
        include 'includes/connection.php';

        try {
            $sql = 'SELECT * FROM item;';
            $resultSet = $pdo->query($sql);
        } // end try
        catch (PDOException $e) {
            echo 'Error fetching items: ' . $e->getMessage();
            exit();
        } // end catch

        foreach ($resultSet as $row) {
            // put each rows's elements into variables
            $itemName = $row['itemName'];
            $unitPrice = $row['unitPrice'];
            $qtyOnHand = $row['qtyOnHand'];
            $thumbNail = $row['thumbNail'];
            $photo1 = $row['photo1'];

            echo '<td><img  src="' .$photo1 .'" width="500" height="500" alt="$itemName" title="$itemName" ></td>';
        }
    ?>

    <p>Content you want the user to see goes here.</p>
Click here to [<a href='#' onclick='overlay()'>close</a>]
    </div>
</div>

<div id="MainHolder">
    <div id="Headerbar">
        <?php
            include 'includes/login.php';
        ?>
        <div class="ContentBody">
            <div class="Content">
                <article> 
                    <h2>Store</h2>
                    <?php
                        include 'includes/connection.php';
                        try
                        {
                            $sql = 'SELECT * FROM item;';
                            $resultSet = $pdo->query($sql);
                        } // end try
                        catch (PDOException $e)
                        {
                            echo 'Error fetching items: ' . $e->getMessage();
                            exit();
                        } // end catch
                    ?>
                    <!-- open table -->

                    <article>
                    <?php
                        // read result set and populate table 
                        foreach ($resultSet as $row)
                        {
                            // put each rows's elements into variables
                            $itemName = $row['itemName'];
                            $thumbNail = $row['thumbNail'];
                            $qtyOnHand = $row['qtyOnHand'];
                            // test for out of stock condition
                            // if no stock, display out of stock image else display add to cart image 
                            if ($qtyOnHand <= 0) {
                                echo '<td><img  src="images/outOfStock.png" border="3" class="floatingImage" height="80" width="80" alt="" title=""></td>';
                            } else {
                                echo '<td><img class="floatingImage" border="3" src="' .$thumbNail .'" width="80" height="80" alt="' .$itemName .'" title="' .$itemName .'" onclick="overlay()" ></td>';
                            }
                        } // end foreach
                        // close table 
                        echo '</article>';
                    ?>
                </article>
             </div>
             <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
        </div>          
    </div>
</div>

Javascript:

function overlay() {
    el = document.getElementById("overlay");
    el.style.visibility = (el.style.visibility == "visible") ? "hidden" : "visible";
}

The overlay and catalog are in the same file. I'm still learning, so my apologies for any messy formatting/code.

EDIT: I've merged some of the code, this shows pretty much my whole store page other than Headers, ect...

You need to edit your overlay function to send the itemName to server, this will tell your server which item the user clicked on.

overlay function:

function overlay() {

    var item = this.getAttribute("title");//this gets the name of item that was clicked
}

Now we need to set up an ajax request to the server.

function ajaxRequest(item) {
  if (window.XMLHttpRequest){
    var xmlhttp= new XMLHttpRequest();
    xmlhttp.onreadystatechange=function(){
      if (xmlhttp.readyState==4 && xmlhttp.status == 200){//show the overlay after we recieve a response from the server
        el = document.getElementById("overlay");
        el.style.visibility = (el.style.visibility == "visible") ? "hidden" : "visible";
        el.innerHtml = ''; //remove previous response
        el.innerHTML=xmlhttp.responseText; //insert the response in your overlay
      }
    }
    xmlhttp.open("GET","overlay.php?item="+ encodeURIComponent(item),true);
    xmlhttp.send();
  }
}

Now we need to edit the overlay function to make a call to the ajaxRequest function:

function overlay() {

    var item = this.getAttribute("title");//this gets the name of item that was clicked
    ajaxRequest(item); //send the item name to server
}

After doing this, your PHP will receive a the variable on your server. Create a new file called overlay.php and insert the following code. Save this file in the same directory as your Store.php file.

overlay.php:

<?php
if (isset($_GET['item'])) {//check if you received the name
    $itemName = $_GET['item'];

   //query database for the itemName

                        try
                        {
                            $sql = 'SELECT * FROM item WHERE itemName ='.$itemName.';';//just select data with the matching item name.
                            $resultSet = $pdo->query($sql);
                        } // end try


                        catch (PDOException $e)
                        {
                            echo 'Error fetching items: ' . $e->getMessage();
                            exit();
                        } // end catch
    //fetch the data
    foreach ($resultSet as $row) {
        // put each rows's elements into variables
        $itemName = $row['itemName'];
        $unitPrice = $row['unitPrice'];
        $qtyOnHand = $row['qtyOnHand'];
        $thumbNail = $row['thumbNail'];
        $photo1 = $row['photo1'];
    echo '<td><img  src="' .$photo1 .'" width="500" height="500" alt="$itemName" title="$itemName" ></td>';
    }//end foreach

}//end if
?>

如果要绝对在客户端存储数据,则可以将html5的本地存储功能与嵌入式sql lite数据库一起使用,以使用Javascript存储和检索信息。

When you first get the Product from the DB using this loop:

foreach ($resultSet as $row) {
    // put each rows's elements into variables
    $itemName = $row['itemName'];
    $unitPrice = $row['unitPrice'];
    $qtyOnHand = $row['qtyOnHand'];
    $thumbNail = $row['thumbNail'];
    $photo1 = $row['photo1'];
    echo '<td><img  src="' .$photo1 .'" width="500" height="500" alt="$itemName" title="$itemName" ></td>';
}

Are those all the attributes that you want to show when the User clicks on the image for the overlay? If so, just store the values in the actual <img> tag:

    echo '<td><img src="' .$photo1 .'" width="500" height="500" alt="$itemName" title="$itemName" data-unit-price="$unitPrice" data-qty="$qtyOnhand"></td>';

Then you can use Javascript to access the data and show in your overlay.

I try to understand your problem and used jQuery to solve it.

First you have to load jQuery lib

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>

And add display:none style to every production info in overlay(default is hidden).

echo '<td><img src="' .$photo1 .'" width="500" height="500" alt="$itemName" title="$itemName" style="display:none" ></td>';

Remove thumbnail inline onClick event trigger

echo '<td><img class="floatingImage" border="3" src="' .$thumbNail .'" width="80" height="80" alt="' .$itemName .'" title="' .$itemName.'"'></td>';

Add this click event handler thus jQuery can show the production info which user clicked.

$(".floatingImage").click(function(){
    var itemName = $(this).attr('alt');
    $('#overlay img').hide();
    $('#overlay img[alt="'+itemName+'"]').show();
    overlay();
});

Hope this is helpful for you.

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