开发者

how to do this using ajax?

Hi could someone please explain to me to how i can accomplish this using ajax so there is no page refresh. I am new to using ajax and jquery in general and any help and explanation would be great.

This is my php code.

<div class="recentwork">
<div class="imgholderfloat">
<?php
include 'process/connect.php';
$small_path = "/work/small/";
$large_path = "/work/large/";
$full_path  = "/work/full/";


$per_page = 3;
$pages_query = "SELECT id FROM projects";
$pages_result = mysqli_query( $link, $pages_query );
$pages = ceil(mysqli_num_rows($pages_result) / $per_page);

if ($_GET['page'] > $pages) {
    $page = 1;
} else {
$page = (isset($_GET['page'])) ? (int)$_GET['page'] : 1;
}
$start = ($page - 1) * $per_page;



$query = " SELECT * FROM projects INNER JOIN orders ON orders.id = projects.order_id LIMIT $start, $per_page";
$result = mysqli_query( $link , $query );
$num_rows = mysqli_num_rows($result);                               

while ($row = mysqli_fetch_assoc($result)){
echo '<div class="imgholder"><a href="'.$full_path.''.
    $row['filename'].'"><img src="'.$small_path .''.$row['filename'].'" /></a><div class="largeimg"><a href="'.$full_path.''.$row['filename'].'"><img src="'.$large_path.''.$row['filename'].'" /></a></div>
<div class="details">
<p><span class="red">Theme</span>: '.$row['theme'].'</p>
<p><span class="red">Budget</span>: '.$row['budget'].'</p>
<p><span class="red">Type</span>: '.$row['type'].'</p>
<p><span class="red">Misc</span>: '.$row['misc'].'</p>
</div>
</div>
';
}
if ($pages > 1 && $page < $pages) {
    echo '&开发者_开发百科lt;span class="morebtn" ><a href="?page='. $page= $page + 1 .'" >MORE</a></span>';
} 
else {
    echo '<span class="morebtn" ><a href="?page='. $page= $page - 1 .'" >BACK</a></span>';
}
?>

</div>
</div>

So basically its a simple pagination displaying divs which hold pictures etc retrieved from a database. How do i send the particular get statement via ajax so that the next set of divs is updated without page refresh. I have attempted it by myself but could not figure it out.

Thanks again.

Ok so this is as far as i can get. How do i get about displaying what is retrieved? I have looked on the internet but there is so many different ways of doing this i cant understand which and why you would do it a particular way.

$("a#morebutton").click(function() {
  e.preventDefault();   
  $.ajax({  
  type: "GET",  
  url: index.php+$('a#morebutton').attr('href') ,
}); 
e.preventDefault();   
});


From reading your code, I assume this is what you want:

$(".morebtn a").click(function(e) {
    e.preventDefault();

    $.get("index.php"+$(this).attr("href"), function(result) {
        $(".imgholderfloat").html(result);
    });
}


I think it makes more sense to demonstrate the concepts behind how to change an image using a GET request in Ajax. How you accommodate doing this in your code is a matter of how you organize your code, but it can nevertheless be done in a couple of different ways.

Below, I will demonstrate a method to return an HTML snippet with the <img .../> to replace the current image and handle errors, the first/last/previous/next concerns, and so forth. This is meant to show you how you may do it in an abstract case; how you do it in the end with your code will ultimately be up to you. Make sure and read the comments in the code below for explanations of what I'm doing.

To see the below in action, see: http://jfcoder.com/test/getimages.php

NOTE: I do not send all of the HTML until after I have determined the snippet. This allows me to handle both requests with one PHP script. You can, however, do this with two different scripts.

<?php 

// My ad hoc array of images. You of course will be 
// generating this list from a database call.

$images = array(
    'http://upload.wikimedia.org/wikipedia/commons/d/db/087882_cf786e35-by-Roger-May.jpg',
    'http://upload.wikimedia.org/wikipedia/commons/6/6c/173865_d45f46f7-by-dave-challender.jpg',
    'http://upload.wikimedia.org/wikipedia/commons/9/97/188798_e4bc708f-by-Stephen-McKay.jpg',
    'http://upload.wikimedia.org/wikipedia/commons/c/c0/205765_f6ccbfdb-by-Stephen-G-Taylor.jpg'
);

// I use a switch to determine full html or just a
// snippet to return. Note, it defaults to full.

switch ($_GET['type']) {
    case 'snippet': 
        $type = 'snippet';
        break;
    default:
        $type = 'full';
}

// Determine the current, first, and last ids.

$imgid = (int) $_GET['img'];
$first = 0;
$last = count($images) - 1;

// If it's not real, reset to the beginning photo.

if (!$images[$imgid]) {
    $imgid = 0;
}

// Here I determine what the previous and last img ids
// will be.

$previous = ($imgid < 1 ? $last : $imgid - 1);
$next = ($imgid >= $last+1 ? 0 : $imgid + 1);

// If I just need to return a snippet, then do that and
// exit. This prevents the full code from returning,
// and does so based on the GET `type` value provided.

if ($type == 'snippet') {
    echo "<img class='view' src='{$images[$imgid]}'/>";
    exit;
}

// This will output the full page. Note, it also
// accounts for when the Ajax produces an error, since
// it will respond correctly to a URL with no `type`
// provided and with an `img` value.

echo <<<HTML
<html>
<head>
<style type="text/css">
</style>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js"></script>
<script type="text/javascript">

$(document).ready(function(){
    $('.browse').click(function(){
        that = $(this);
        // I use the `rel` attribute to store image-
        // related data. Each ANCHOR has the reference
        // to the imgid it needs to request the correct
        // image snippet.
        var imgid = that.attr('rel');
        // I need this for errors. This allows me to
        // show the image by bypassing the Ajax call when
        // it doesn't work correctly.
        var href = that.attr('href');
        $.ajax({
            // Note, `get` is default, but I provided it
            // for demonstration purposes and to make it
            // clear this is what is happening.
            type: 'get',
            // Note the `type=snippet` part.
            url: 'getimages.php?type=snippet&img='+imgid,
            // What to do when the Ajax call appears to 
            // complete successfully.
            success: function(data){
                // If the server didn't respond with an
                // `<img .../>` tag, send the browser to
                // the `href` instead. 
                if (data.indexOf('<img') == -1) {
                    window.location = href;
                }
                // I'm going to replace the image with the
                // new image I just got.
                $('.view').replaceWith(data);
                // The bits that manipulate the current
                // page's values for next and previous.
                // Note the use of the `rel` tag here.
                var first = $('#first').attr('rel');
                var last = $('#last').attr('rel');
                var previous = $('#previous').attr('rel') - 1;
                var next = $('#next').attr('rel') - 0 + 1;
                if (previous < 0) previous = last;
                if (next > last || next == last) next = 0;
                $('#previous').attr('rel', previous);
                $('#next').attr('rel', next);
            },
            // Again, if the Ajax call errors out, I simply
            // send the browser to the url found in the `href`.
            error: function(){
                window.location = href;
            }
        });
        // Cancel the browser following the `href` tag.
        return false;
    });
});

</script>
</head>
<body>
<div>
<img class="view" src="{$images[$imgid]}"/>
<p>
 <a class="browse" id="first" rel="$first" href="?img=$first">First</a>
 <a class="browse" id="previous" rel="$previous" href="?img=$previous">Previous</a>
 <a class="browse" id="next" rel="$next" href="?img=$next">Next</a>
 <a class="browse" id="last" rel="$last" href="?img=$last">Last</a>
</p>
</div>
</body>
</html>
HTML;

?>

What the browser will see when visiting http://jfcoder.com/test/getimages.php:

<html>
<head>
<style type="text/css">
</style>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js"></script>
<script type="text/javascript">

$(document).ready(function(){
    $('.browse').click(function(){
        that = $(this);
        // I use the `rel` attribute to store image-
        // related data. Each ANCHOR has the reference
        // to the imgid it needs to request the correct
        // image snippet.
        var imgid = that.attr('rel');
        // I need this for errors. This allows me to
        // show the image by bypassing the Ajax call when
        // it doesn't work correctly.
        var href = that.attr('href');
        $.ajax({
            // Note, `get` is default, but I provided it
            // for demonstration purposes and to make it
            // clear this is what is happening.
            type: 'get',
            // Note the `type=snippet` part.
            url: 'getimages.php?type=snippet&img='+imgid,
            // What to do when the Ajax call appears to 
            // complete successfully.
            success: function(data){
                // If the server didn't respond with an
                // `<img .../>` tag, send the browser to
                // the `href` instead. 
                if (data.indexOf('<img') == -1) {
                    window.location = href;
                }
                // I'm going to replace the image with the
                // new image I just got.
                $('.view').replaceWith(data);
                // The bits that manipulate the current
                // page's values for next and previous.
                // Note the use of the `rel` tag here.
                var first = $('#first').attr('rel');
                var last = $('#last').attr('rel');
                var previous = $('#previous').attr('rel') - 1;
                var next = $('#next').attr('rel') - 0 + 1;
                if (previous < 0) previous = last;
                if (next > last || next == last) next = 0;
                $('#previous').attr('rel', previous);
                $('#next').attr('rel', next);
            },
            // Again, if the Ajax call errors out, I simply
            // send the browser to the url found in the `href`.
            error: function(){
                window.location = href;
            }
        });
        // Cancel the browser following the `href` tag.
        return false;
    });
});

</script>
</head>
<body>
<div>
<img class="view" src="http://upload.wikimedia.org/wikipedia/commons/d/db/087882_cf786e35-by-Roger-May.jpg"/>
<p>
 <a class="browse" id="first" rel="0" href="?img=0">First</a>
 <a class="browse" id="previous" rel="3" href="?img=3">Previous</a>

 <a class="browse" id="next" rel="1" href="?img=1">Next</a>
 <a class="browse" id="last" rel="3" href="?img=3">Last</a>
</p>
</div>
</body>
</html>

And what my $.ajax() will see from http://jfcoder.com/test/getimages.php?type=snippet&img=1 (based on the link clicked and the image being viewed):

<img class='view' src='http://upload.wikimedia.org/wikipedia/commons/6/6c/173865_d45f46f7-by-dave-challender.jpg'/>


In conjuction with the use of jQuery, you could try something along the lines of;

$("a#morebutton").click(function() {
    var xhr = new XMLHttpRequest();
    var result_target=$('#imgholder');
    xhr.open("get", "index.php"+this.href, true);
    xhr.onreadystatechange = function(){
        if (xhr.readyState == 4){
            if(xhr.status >= 200 && xhr.status < 300){ 
                $(result_target).html(xhr.responseText);
            }
        }           
    };
    xhr.send(null);
});

Thats purely off the top of my head, I use this format for all my own XHR calls, may need some tweaking to get it running as you wish.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜