AJAX图像滑块

Hello fellow programmers,

This is my first time using AJAX so I really need some help (project deadline is next week, only a couple more things and I'm done).

So the theory is the following:

I'm working on a student project, a website where people can advertise their housing for sale.

It has a MySQL Database that holds relevant information of the User and the Property. In regards to the property I have 2 tables:

  • property (stores the id_property, id_user, name, description, address, etc...)
  • propertyimages (stores id_property, id_image, path, uploaddate)

What I need is AJAX code that will show the images, one at a time, until the user clicks on the image itself or on a next/previous button underneath it, creating a slideshow, and automatically fill in a hidden textbox with the id_image of the current image, so the user can click on a button/link that will delete the image from the database.

This is my code so far:

<?php session_start()?>
<?php include 'w3.html'; ?>
        <!-- put <title> code under here -->
<?php include 'essentialhead.html'; ?>
        <!-- put <head> code under here -->

<?php include 'closeheadopenbody.html'; ?>
            <!-- header -->
            <?php include 'header.html'; ?>
            <!-- content -->
            <?php include 'row1clear.html'; ?>
                    <?php 
                        $urlexplode = explode('?', "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]");
                        $token = end($urlexplode);

                        $connection = mysql_connect("localhost","root")
                                        or die("Problem connecting to MySQL!");
                        mysql_select_db("imobili");

                        $propertyquery = mysql_query("SELECT * 
                                                      FROM property 
                                                      WHERE id_property='".$token."'");             
                        $rowproperty = mysql_fetch_array($propertyquery);
                        echo $rowproperty['name'];
                    ?>
            <?php include 'row2clear.html'; ?>
                    <?php
                        echo'<div class="profilewrapper">
                                <div class="propertyslideshow">
                                    <div class="tablecell">
                                        <div id="slide" class="slider">'; **HERE IS WHERE I NEED AJAX TO SHOW THE IMAGES**
                                            $imagesquery = mysql_query("SELECT * 
                                                              FROM propertyimages
                                                              WHERE id_property='".$rowproperty['id_property']."'");                
                                            while($rowimage = mysql_fetch_array($imagesquery))
                                            {
                                                echo'<img class="sliderimg" alt="no image" src="'.$rowimage['path'].'">';                               
                                            }

                        echo'           </div>
                                    </div>
                                </div>
                                <div class="propertytools">'; **IF THE USER IS THE OWNER OF THE PROPERTY, OR AN ADMINISTRATOR, HE GETS ACCESS TO THE FOLLOWING 3 TOOLS: USE AS MAIN PHOTO, DELETE CURRENT IMAGE, AND DELETE PROPERTY**
                                    if($_SESSION['username'] == $rowproperty['username'] or $_SESSION['permissions'] == 'admin')
                                    {
                                    echo'<form class="property" method="post" name="uploadform" action="" enctype="multipart/form-data">
                                         <fieldset>
                                         <legend>Upload another image</legend>
                                         <input type="file" id="foto" name="foto"/><input class="submit" type="submit" value="Submit"/>
                                         </fieldset>
                                         </form>
                                         <form class="property" method="post" name="uploadform" action="">
                                         <input type="hidden" name="currentimgid" value="**I NEED THE id_img here in real time!**"/>


                                         <input onclick="submitform()" class="submitlink" type="submit" id="propform" name="setprev" value="Use this image as Preview"/>
                                         **THE INPUT BELOW WILL POST THE id_image**
                                         <input onclick="submitform()" class="submitlink" type="submit" id="propform" name="delimg" value="Delete this image"/>
                                         <input onclick="submitform()" class="submitlink" type="submit" id="propform" name="delprop" value="Delete this property"/>
                                         <script>
                                            function submitform()
                                            {
                                                var r=confirm("Are you sure?");
                                                if(r==true)
                                                {
                                                    document.propform.submit();
                                                }
                                            }
                                         </script>
                                         </form>';
                                    }
                        echo'   </div>
                                <div class="propertydetails">
                                    <div class="profiledetails">Date Of Construction</div>'.$rowproperty['dateconstruction'].'
                                    <div class="profiledetails">Rent</div>'.$rowproperty['rentvalue'].'
                                    <div class="profiledetails">Sell</div>'.$rowproperty['sellvalue'].'
                                </div>
                            </div>';



                        echo'   <form class="comment" name="commentform" action="">
                                Leave a comment<br>
                                <textarea name="commentinput"></textarea>
                                <input type="submit" class="submit" value="Send">
                                </form>';
                            mysql_close();
                    ?>
                    <?php
                        if(ISSET($_POST['delprop']))
                        {
                            echo'';
                            $sql = "DELETE FROM property
                                   WHERE id_property = ".$token;
                            mysql_query($sql);

                            $sql = "DELETE FROM propertyimages
                                   WHERE id_property = ".$token;
                            mysql_query($sql);
                        }
                    //var_dump($_FILES['foto']);
                        if(ISSET($_FILES['foto']))
                        {
                            $username = $_SESSION['username'];
                            //upload
                            $allowedExts = array("gif", "jpeg", "jpg", "png", "JPG");
                            $explode = explode(".", $_FILES["foto"]["name"]);
                            $extension = end($explode);
                            //var_dump($extension);
                            if ((($_FILES["foto"]["type"] == "image/gif")
                            || ($_FILES["foto"]["type"] == "image/jpeg")
                            || ($_FILES["foto"]["type"] == "image/jpg")
                            || ($_FILES["foto"]["type"] == "image/pjpeg")
                            || ($_FILES["foto"]["type"] == "image/x-png")
                            || ($_FILES["foto"]["type"] == "image/png"))
                            && ($_FILES["foto"]["size"] < 200000000) //20MB
                            && in_array($extension, $allowedExts))
                            {
                                if ($_FILES["foto"]["error"] > 0)
                                {
                                echo "Return Code: " . $_FILES["foto"]["error"] . "<br>";
                                }
                                else
                                {
                                echo "Upload: " . $_FILES["foto"]["name"] . "<br>";
                                echo "Type: " . $_FILES["foto"]["type"] . "<br>";
                                echo "Size: " . ($_FILES["foto"]["size"] / 1024) . " kB<br>";
                                echo "Temp file: " . $_FILES["foto"]["tmp_name"] . "<br>";
                                $path1 = "upload/".$username;
                                echo $path1;
                                $path2 = "upload/".$username."/".$token;
                                    $dest = "upload/".$username."/".$token. "/". $_FILES["foto"]["name"];
                                    echo $dest;
                                    if (file_exists("upload/" . $_FILES["foto"]["name"]))
                                    {
                                        echo $_FILES["foto"]["name"] . " already exists. ";
                                    }
                                    else
                                    {
                                    if ( ! is_dir($path1)) {
                                        mkdir($path1);
                                    }
                                    if ( ! is_dir($path2)) {
                                        mkdir($path2);
                                    }
                                    move_uploaded_file($_FILES["foto"]["tmp_name"], $dest);
                                    }
                                }
                            $datetime = date_create()->format('Y-m-d H:i:s');
                            $sqlimages = "INSERT INTO propertyimages (path, uploaddate, id_property) VALUES('$dest', '$datetime', '$token')";                       
                            //var_dump($sqlimages);
                            mysql_query($sqlimages);
                            }
                            else
                            {
                                echo "<script>alert(\"Wrong extension\")</script>";
                            }
                        }
                    ?>
            <?php include 'contentclose.html'; ?>
            <!-- footer -->
            <?php include 'footer.php'; ?>
  1. You have to show only the first image to user.
  2. White down the current image to session.
  3. Make a button which request the next image.
  4. When the next image is taken from server, white down in the same session the new image index and proceed. I can not write you the code it is complicated.

Using a utility library like jQuery will help you immensely here. Have a look at the $.ajax() method and you should be able to grasp it from there. There is also $.post() which is a shorthand version to send and retrieve data from the server. For example:

$('.button').on('click', function(e) {
    e.preventDefault();

    $.post('url.php', { data: 'here' }, function(result) {
        // `result` contains the server response
    });
});

url.php would just be a normal PHP script accepting POST data. Any thing echoed is sent back to the callback function in result.