UPDATE:
At this moment I have a basic working instagram image display on my website.
What I like to create is a "load next 12 images" button. When I use "max_id=" directly in my url it is working fine.
Can someone point me in the correct direction to make this work?
This is what I have right now:
<style>
section.instagram img {
float:left;
height: 200px;
margin: 10px;
}
</style>
<?php
$otherPage = 'nasa';
$response = file_get_contents("https://www.instagram.com/$otherPage/?__a=1");
if ($response !== false) {
$data = json_decode($response, true);
$userdata = $data['user'];
$mediadata = $data['user']['media']['nodes'];
if ($data !== null) { ?>
<section class="instagram">
<?php
$cnt = count($mediadata) > 12 ? 12 : count($mediadata);
echo $cnt;
for($i = 0; $i < $cnt; $i++){
?>
<img src="<?php echo $mediadata[$i]['thumbnail_src']; ?>" alt="">
<?php
}
?>
</section>
<?php
} // end of response check
} // end of data null
?>
i just finished a code that does that, but im using javascript, here it is!
<!DOCTYPE html>
<html>
<body>
<p id="add-data"></p>
<a id="LoadMore" >Load More</a>
<!--Add jquery-->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.js"></script>
<script>
//Add your token
var token = '[your access token]';
//Declare the var to save the nexturl from the API
nexturl = '';
//First call will load at the beginning of the site
$.ajax({
//Modify the count value to set how many photos you want to load
url: 'https://api.instagram.com/v1/users/self/media/recent/?access_token='+ token + '&count=12',
dataType: 'jsonp',
type: 'GET',
data: {access_token: token},
success: function(data){
//Gather The images of the User
for(i =0;i < data.data.length ;i++){
//this variables are just to save the data and simplify you
// can also use the data.data[] info instead
img = data.data[i].images.low_resolution.url;
img_link = data.data[i].link;
likes = data.data[i].likes.count;
comments = data.data[i].comments.count;
interactions = data.data[i].comments.count + data.data[i].likes.count;
//Appends the variables inside the div
$("#add-data").append("<img src='" + img +"' width='150px' height='150px'> <p>Likes: "+likes+"</p><p>Comments: "+comments+"</p><p>Total Interactions: "+interactions+"</p></div><div class='card-action'><a href='" + img_link + "'>Check Photo</a> ");
}
nexturl = data.pagination.next_url;
},
error: function(data){
console.log(data)
}
});
//Load More Photos From Instagram
//If you click on the Load More text / button / etc it will run again the code
//adding the next 12 photos
$('#LoadMore').click(divFunction);
function divFunction(e){
e.preventDefault();
//Each request from instagram can handle only 33 Images (that's how the API works')
$.ajax({
url: nexturl, // we don't need to specify parameters for this request - everything is in URL already
dataType: 'jsonp',
type: 'GET',
success: function(data){
for(x in data.data){
img = data.data[x].images.low_resolution.url;
img_link = data.data[x].link;
likes = data.data[x].likes.count;
comments = data.data[x].comments.count;
interactions = data.data[x].comments.count + data.data[x].likes.count;
//console.log('Image ID: ' + img_id + ' Image Link: ' + img_link + ' Likes: ' + likes);
i ++;
$("#add-data").append("<div class='col s4'><div class='card horizontal'><div class='card-image'><img src='" + img +"' width='150px' height='150px'></div><div class='card-stacked'><div class='card-content'><p >Likes: "+likes+"</p><p>Comments: "+comments+"</p><p>Total Interactions: "+interactions+"</p></div><div class='card-action'><a href='" + img_link + "'>Check Photo</a></div></div></div></div>");
}
nexturl = data.pagination.next_url;
console.log(tot_nexturl)
},
error: function(result2){
console.log(result2);
}
});
}
</script>
</body>
</html>
Hope this helps !
Related
I have a code for showing list from database and a loadmore button. After all records list is displayed and click on loadmore button show empty places.
How to hide loadmore button once all records displayed?
index.php file:
<?php $chinp=$_GET['schinp'];?>
<div id="schts"></div>
<button id="btnsch">load more</button>
<script>
$(document).ready(function() {
var chinp="<?php echo $chinp;?>";
var srchco = 1;
var offsrch = 0;
$("#btnsch").click(function() {
$.ajax({
method: "POST",
url: "search.php",
data: { srchcoun: srchco, offsrch: offsrch ,chinp:chinp}
})
.done(function(msg) {
$("#schts").append(msg);
});
offsrch = offsrch + srchco;
});
$("button").trigger("click");
});
</script>
search.php :
$srchcoun=$_POST['srchcoun'];
$offsrch=$_POST['offsrch'];
$chinp=$_POST['chinp'];
$schql="SELECT id, name, lastname FROM t_users WHERE name LIKE '$chinp' ORDER BY name ASC limit $offsrch, $srchcoun";
$rsch=mysqli_query($conn,$schql);
while ($rch=mysqli_fetch_assoc($rsch)){
$scid=$rch['id'];$snm=$rch['name'];$slnm=$rch['lastname'];?>
<div class="alsu">
<img class="sask" src="pic/<?php echo $scid;?>.png" alt="">
<span class="snm">Name : <?php echo $snm." ".$slnm;?></span>
</div>
<?php }?>
</div>
Thanks.
Here is code to hide load more button as per your code.
Replace this code in your first file.
<script type="text/javascript">
$(document).ready(function() {
var chinp="<?php echo $chinp;?>";
var srchco = 2;
var offsrch = 0;
var page_num = 0;
$("#btnsch").click(function() {
$.ajax({
method: "POST",
url: "search.php",
data: { srchcoun: srchco, offsrch: offsrch ,chinp:chinp, page_num : page_num}
})
.done(function(msg) {
if(msg == 'noMoreData'){
$("#btnsch").hide();
} else {
$("#schts").append(msg);
}
});
page_num = page_num + 1;
offsrch = offsrch + srchco;
});
$("#btnsch").trigger("click");
});
</script>
Now add this code in your search file.
<?php
$srchcoun=$_POST['srchcoun'];
$offsrch=$_POST['offsrch'];
$chinp=$_POST['chinp'];
$page_num=$_POST['page_num'];
$total_records = 0;
$totalschql="SELECT id FROM t_users WHERE name LIKE 'krishna' ORDER BY name ASC";
if ($result=mysqli_query($conn,$totalschql))
{
$total_records=mysqli_num_rows($result);
}
$last_records_count = ($page_num) * $srchcoun;
if($last_records_count >= $total_records) {
echo 'noMoreData';exit();
} else {
$schql="SELECT id, name, lastname FROM t_users WHERE name LIKE '$chinp' ORDER BY name ASC limit $offsrch, $srchcoun";;
$rsch=mysqli_query($conn,$schql);
while ($rch=mysqli_fetch_assoc($rsch)){
$scid=$rch['id'];$snm=$rch['name'];$slnm=$rch['lastname'];
?>
<div class="alsu">
<img class="sask" src="pic/<?php echo $scid;?>.png" alt="">
<span class="snm">Name : <?php echo $snm." ".$slnm;?></span>
</div>
<?php }?>
</div>
<?php
}
?>
Try this and let me know if you have any issue.
Simply use $('#myButtonId').hide(); in ajax part after you load the entire data from database.
function get_rain_data_list(is_load_more=0){
if(is_load_more!=0){//if is_load_more is not 0 then get offset data from btnlod attr
offset = $('#btn_load_more_rain').attr("data-offset");
}else{ //set offset =0 when is_load_more is 0
offset = 0;
}
var id = $('#id').val();
var countShow = 0;
if(fromDate!=''){
countShow = 1;
}
$.ajax({
url: base_url+"rain_data_list_ajax",
type: "POST",
data:{offset:offset,propertyId:propertyId,fromDate:fromDate,toData:toData},
dataType: "JSON",
beforeSend: function() {
show_loader();
},
success: function(data){
hide_loader();
// console.log(data);
$('.proprty_load_more_btn').remove();//remove load more button
if(offset==0){ //clear div when offset 0
$("#append_rain_list").html('');
}
if(data.no_record==0){//show data in div when no previous record
$("#append_rain_list").html(data.html_rain);
$("#add_count").html('');
if(countShow){
//$("#add_count").html(data.count+data.record);
}
}else{
//append data when already record show in view
$("#append_rain_list").append(data.html_rain);
$("#append_load_btn").append(data.btn_html);
$("#add_count").html('');
if(countShow){
$("#add_count").html(data.count+data.record);
}
}
},
});
}
<div id="append_rain_list"></div>
<div id="add_count"></div>
<?php
function rain_data_list_ajax(){
$limit = 6;
$is_next = 0;
//get and set offset
$offset = $this->input->post('offset');
$data['property_id'] = decoding($this->input->post('propertyId'));
$fDate = sanitize_input_text($this->input->post('fromDate'));
$tDate = sanitize_input_text($this->input->post('toData'));
$new_offset = $limit+$offset; //pr($data);
//set where
$where = array('property_id'=>$data['property_id']);
//set select field to get
$data['limit'] = $limit;
$data['offset'] = $offset;
//get count of records
$dataView['total_count'] = $this->Property_model->get_rain_count($data);
//get records
$dataView['rain_list'] = $this->Property_model->get_rain_list($data);
///lq();
//check for load more btn
//pr($dataView);
if($dataView['total_count']>$new_offset){
$is_next =1;
}
$btn_html = '';
if($is_next){
//if is next =1 set load more button in btn_html
$id = "btn_load_more_rain";
$btn_html = '<div class="col-sm-12 text-center pt-20 proprty_load_more_btn"><button class="login-btn load load_more_btn" id = "'.$id.'" data-offset ="'.$new_offset.'" data-isNext ="'.$is_next.'" >'.lang('load_more').'</button></div>';
}
//load view with data
$html_rain = $this->load->view('test1',$dataView,true);
$response = array('status'=>1,'html_rain'=>$html_rain,'btn_html'=>$btn_html,'count'=>$dataView['total_count'],'record'=>lang('recod_found'));
//flag for no record
$no_record=1;
if(empty($dataView['rain_list'])){
$no_record = 0;
}
$response['no_record'] = $no_record;
echo json_encode($response);die;
}
?>
<li>
<a id="collection" href="collections.php">
<span class="glyphicon glyphicon-th white"> Collections</span>
</a>
</li>
<script>
$(document).ready(function(){
$("#collection").click(function(){
$.ajax({
type: 'POST',
url: 'pagination.php',
success: function(data) {
$('#cont').show();
}
});
});
});
</script>
pagination.php :
<?php
require_once "database.php";
$db = new Database();
$perPage = 9;
$page = (isset($_GET['page'])) ? (int)$_GET['page'] : 1;
$startAt = $perPage * ($page - 1);
$queryTotalRow = "SELECT COUNT(*) FROM image";
$rsetTotalRow = $db->query($queryTotalRow);
$fetchTotalRow = mysqli_fetch_array($rsetTotalRow);
$totalPages = ceil($fetchTotalRow["0"] / $perPage);
$links = "";
for ($i = 1; $i <= $totalPages; $i++) {
$links .= ($i != $page ) ? "<li><a href='collections.php?page=$i'>Page $i</span></a></li> "
: "<li><a href='collections.php?page=$i'>Page $page</a></li> ";
}
$paginationQuery = "select name,image,price,description from image LIMIT $startAt, $perPage";
$result = $db->query($paginationQuery);
if($result){
echo '<div class="containerCollection" id="cont" style="display:none" >';
while($row = mysqli_fetch_array ($result)){
echo '<div style="float:left" class="divEntry">';
echo "<div align='center' class='nameEntry'>".$row['name']."</div>";
echo '<div align="center"><img src="'.$row['image'].'" class="imageEntry"/></div>';
echo "<div align='center' class='priceEntry'>".$row['price']."</div>";
echo "<div class='descEntry'>".$row['description']."</div>";
echo '</div>';
}
echo "<div class='text-center' style='clear:both'>";
echo "<ul class='pagination'>";
echo $links;
echo '</ul>';
echo '</div>';
echo '</div>';
}
?>
why is this not working ? i trigger an ajax call from collection button click , then i want to return some echoes wrapped in div which i set to hide, then i want to show it.
edit : fully updated my pagination.php seems like at fault .
edit2 : solver using this solution jQuery showing div and then Disappearing
Your response isn't on the page yet. You've just echoed it in a Ajax call.
In your success function take the returned data put it on the page then try and show it i.e
success: function(data) {
$('body').append(data);
$('body #cont').show();
}
This is assuming the data is being returned correctly, I'd put something in our pagination.php that says return json_encode($row) then you have the data in a JSON format in your success function to build the elements you want.
Check your payload and responses in the browser when running the code make sure it returns data. You can then specify an explicit html type to be returned in your ajax, finally append the html like follow:
Apply html:
<!--html-->
<html>
<head>
<script language="javascript" type="text/javascript" src="jquery-1.11.3.js"></script>
<script language="javascript" type="text/javascript" src="script.js"></script>
</head>
<body>
<h1>Test header</h1>
<h2 id="idTxt"></h2>
</body>
</html>
Apply javascript:
//javascript
$(document).ready(function() {
var data = 'name=getData'; //data parameter passed through to execute specific functions
$.ajax({
type: "POST",
url: "function.php",
data: data,
dataType: 'json',
success: function(data) {
$("#idTxt").append(data["html"]);
console.log(data["html"]);
},
error: function(data) {
//console.log(data);
}
});
});
Apply php:
//php
<?php
if (isset($_POST["name"]))
{
$string = "<h4> Hi there </h4>"; //build up html as string
$obj = new stdClass();
$obj->html = $string;
echo json_encode($obj);
}
?>
Also try to replace your POST with a get maybe, remember you are trying to get html response data from the server. Good luck hope it helps. :)
I currently had found bootstrap image gallery from here https://blueimp.github.io/Bootstrap-Image-Gallery/
I had found that they are using ajax json method to display the image from flikr website. But i currently using php to retrieve the image from database. Anyway i can change the ajax json code to retrieve my image from php other than using json method? Thanks
Here are the ajax json code the code retrieving image from flikr :
// Load demo images from flickr:
$.ajax({
url: 'https://api.flickr.com/services/rest/',
data: {
format: 'json',
method: 'flickr.interestingness.getList',
api_key: '7617adae70159d09ba78cfec73c13be3'
},
dataType: 'jsonp',
jsonp: 'jsoncallback'
}).done(function (result) {
var linksContainer = $('#links'),
baseUrl;
// Add the demo images as links with thumbnails to the page:
$.each(result.photos.photo, function (index, photo) {
baseUrl = 'http://farm' + photo.farm + '.static.flickr.com/' +
photo.server + '/' + photo.id + '_' + photo.secret;
$('<a/>')
.append($('<img>').prop('src', baseUrl + '_s.jpg'))
.prop('href', baseUrl + '_b.jpg')
.prop('title', photo.title)
.attr('data-gallery', '')
.appendTo(linksContainer);
});
});
Here are the sample php code i plan to use to retrieve the image from my database:
<?php
include 'dbConnect.php';
global $conn;
if($kiosk=='0'){
$query = "SELECT * FROM M_Photo WHERE photo_kiosk ='$kiosk' AND photo_deleted ='0' ORDER BY photo_name";
}
else{
$query = "SELECT * FROM I_Photo WHERE photo_kiosk ='$kiosk' AND photo_deleted ='0' ORDER BY photo_name";
}
$result = sqlsrv_query($conn,$query);
while( $row = sqlsrv_fetch_array ( $result, SQLSRV_FETCH_ASSOC )){
?>
<li id="image-1" class="thumbnail">
<a style="background-image:url(Upload/<?php echo $row['photo_data']; ?>);background-size: 100px 100px;background-repeat: no-repeat;" title="<?php echo $row['photo_name']; ?>" href="Upload/<?php echo $row['photo_data']; ?>">
<img class="grayscale" src="Upload/<?php echo $row['photo_data']; ?>" alt="<?php echo $row['photo_name']; ?>" style="width:100px; height:100px" ></a>
</li>
<?php
}
sqlsrv_free_stmt($result);
sqlsrv_close($conn);
?>
Anyway to change the ajax code to achieve that?
Try this php code:
<?php
include 'dbConnect.php';
global $conn;
if($kiosk=='0') {
$query="SELECT * FROM M_Photo WHERE photo_kiosk ='$kiosk' AND photo_deleted ='0' ORDER BY photo_name";
} else {
$query="SELECT * FROM I_Photo WHERE photo_kiosk ='$kiosk' AND photo_deleted ='0' ORDER BY photo_name";
}
$result=sqlsrv_query($conn,$query);
while($row=sqlsrv_fetch_array($result,SQLSRV_FETCH_ASSOC)) {
}
$row=json_encode($row);
echo $row;
sqlsrv_free_stmt($result);
sqlsrv_close($conn);
?>
And javascript:
<script type="text/javascript">
$.ajax({
url:'your php file address',
dataType:'json'
}).done(function(result) {
var linksContainer=$('#links'), baseUrl;
$.each(result, function(index,photo) {
baseUrl='Upload/'+photo.photo_data;
$('<a/>').append($('<img>').prop('src','Upload/'+photo.photo_data)).prop('href','Upload/'+photo.photo_data).prop('title',photo.name).attr('data-gallery','').appendTo(linksContainer);
});
});
</script>
I'm using jquery ,ajax and php to implementing infinite scrolling
the image from database
and the code just works one time when i reach the end of a page and show me the message "No More Content" when there is actually content in the database
here is my cod
index.php
<html >
<?php include($_SERVER["DOCUMENT_ROOT"].'/db.php');
$query = "SELECT * FROM photo ORDER by PhotoNo DESC limit 12";
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
$actual_row_count =mysql_num_rows($result);
?>
<head>
<title>Infinite Scroll</title>
<script src="jquery-1.7.2.js" type="text/javascript"></script>
<script type="text/javascript">
var page = 1;
$(window).scroll(function () {
$('#more').hide();
$('#no-more').hide();
if($(window).scrollTop() + $(window).height() > $(document).height() - 200) {
$('#more').css("top","400");
$('#more').show();
}
if($(window).scrollTop() + $(window).height() == $(document).height()) {
$('#more').hide();
$('#no-more').hide();
page++;
var data = {
page_num: page
};
var actual_count = "<?php echo $actual_row_count; ?>";
if((page-1)* 12 > actual_count){
$('#no-more').css("top","400");
$('#no-more').show();
}else{
$.ajax({
type: "POST",
url: "data.php",
data:data,
success: function(res) {
$("#result").append(res);
console.log(res);
}
});
}
}
});
</script>
</head>
<body>
<div id='more' >Loading More Content</div>
<div id='no-more' >No More Content</div>
<div id='result'>
<?php
while ($row = mysql_fetch_array($result)) {
$rest_logo=$row['PhotoName'];
$image="../images/rest/".$rest_logo;
echo '<div><img src='.$image.' /></div>';
}
?>
</div>
</body>
</html>
data.php
<?php
$requested_page = $_POST['page_num'];
$set_limit = (($requested_page - 1) * 12) . ",12";
include($_SERVER["DOCUMENT_ROOT"].'/db.php');
$result = mysql_query("SELECT * FROM photo ORDER by PhotoNo DESC limit $set_limit");
$html = '';
while ($row = mysql_fetch_array($result)) {
$rest_logo=$row['PhotoName'];
$image="../images/rest/".$rest_logo;
$html .= '<div><img src='.$image.' /></div>';
}
echo $html;
exit;
?>
I really nead a help
You see to be setting the variables wrong from a quick look:
var actual_count = "<?php echo $actual_row_count; ?>";
You're using mysql_num_rows() to count the return on your first set of results. But that is limited to 12.
You need to do a second mysql query to get all the images without limi, then count them to get the total number of images in the database.
In index.php your query is only returning 12 rows meaning that $actual_row_count is only ever going to be 12. Instead I would set $actual_row_count to the result of the query "SELECT count
(*) FROM photo".
My personal preference for these sort of things is to return a JSON response which only contains the n responses that are loading and have a template html stored in javascript. The way you've written it will return all the photo's on the last query instead of the last 12 that you want.
I have an image being created with gdimage, which has 40000 5x5 blocks linking to different user profiles and I want that when you hover over one of those blocks, AJAX will go and fetch that profile from the database by detecting the x and y co-ords when it is moved over the image.
Then when it is clicked, with the information it has obtained link to that users profile.
Here is what I have got so far:
Javascript/jQuery:
<script type="text/javascript">
jQuery.fn.elementlocation = function() {
var curleft = 0;
var curtop = 0;
var obj = this;
do {
curleft += obj.attr('offsetLeft');
curtop += obj.attr('offsetTop');
obj = obj.offsetParent();
} while ( obj.attr('tagName') != 'BODY' );
return ( {x:curleft, y:curtop} );
};
$(document).ready( function() {
$("#gdimage").mousemove( function( eventObj ) {
var location = $("#gdimage").elementlocation();
var x = eventObj.pageX - location.x;
var x_org = eventObj.pageX - location.x;
var y = eventObj.pageY - location.y;
var y_org = eventObj.pageY - location.y;
x = x / 5;
y = y / 5;
x = (Math.floor( x ) + 1);
y = (Math.floor( y ) + 1);
if (y > 1) {
block = (y * 200) - 200;
block = block + x;
} else {
block = x;
}
$("#block").text( block );
$("#x_coords").text( x );
$("#y_coords").text( y );
$.ajax({
type: "GET",
url: "fetch.php",
data: "x=" + x + "&y=" + y + "",
dataType: "json",
async: false,
success: function(data) {
$("#user_name_area").html(data.username);
}
});
});
});
</script>
PHP:
<?
require('connect.php');
$mouse_x = $_GET['x'];
$mouse_y = $_GET['y'];
$grid_search = mysql_query("SELECT * FROM project WHERE project_x_cood = '$mouse_x' AND project_y_cood = '$mouse_y'") or die(mysql_error());
$user_exists = mysql_num_rows($grid_search);
if ($user_exists == 1) {
$row_grid_search = mysql_fetch_array($grid_search);
$user_id = $row_grid_search['project_user_id'];
$get_user = mysql_query("SELECT * FROM users WHERE user_id = '$user_id'") or die(mysql_error());
$row_get_user = mysql_fetch_array($get_user);
$user_name = $row_get_user['user_name'];
$user_online = $row_get_user['user_online'];
$json['username'] = $user_name;
echo json_encode($json);
} else {
$json['username'] = $blank;
echo json_encode($json);
}
?>
HTML
<div class="tip_trigger" style="cursor: pointer;">
<img src="gd_image.php" width="1000" height="1000" id="gdimage" />
<div id="hover" class="tip" style="text-align: left;">
Block No. <span id="block"></span><br />
X Co-ords: <span id="x_coords"></span><br />
Y Co-ords: <span id="y_coords"></span><br />
User: <span id="user_name_area"> </span>
</div>
</div>
Now, the 'block', 'x_coords' and 'y_coords' variables from the mousemove location works fine and shows in the span tags, but it's not getting the PHP variables from the AJAX function and I can't understand why.
I also don't know how to make it so when the mouse is clicked it takes the variables taken from fetch.php and directs the user to a page such as "/user/view/?id=VAR_ID_NUMBER"
Am I approaching this the wrong way, or doing it wrong? Can anyone help? :)
Please see the comments about not doing a fetch with every mousemove. Bad bad bad idea. Use some throttling.
That said, the problem is, you're not using the result in any way in the success function.
Your PHP function doesn't return anything to the browser. PHP variables do not magically become available to your client-side JavaScript. PHP simply runs, produces an HTML page as output, and sends it to the browser. The browser then parses the information that was sent to it as appropriate.
You need to modify your fetch.php to produce some properly formatted JSON string with the data you need. It would look something like { userid: 2837 }. For example, try:
echo "{ userid: $user_id, username: $user_name }";
In your success callback, the first argument jQuery will pass to that function will be the result of parsing the (hopefully properly formatted) JSON result so that it becomes a proper JavaScript object. Then, in the success callback, you can use the result, in a way such as:
//data will contain a JavaScript object that was generate from the JSON
//string the fetch.php produce, *iff* it generated a properly formatted
//JSON string.
function(data) {
$("#user_id_area").html(data.user_id);
}
Modify your HTML example as follows:
User ID: <span id="user_id_area"> </span>
Where showHover is a helper function that actually shows the hover.
Here is a pattern for throttling the mousemove function:
jQuery.fn.elementlocation = function() {
var curleft = 0;
var curtop = 0;
var obj = this;
do {
curleft += obj.attr('offsetLeft');
curtop += obj.attr('offsetTop');
obj = obj.offsetParent();
} while ( obj.attr('tagName') != 'BODY' );
return ( {x:curleft, y:curtop} );
};
$(document).ready( function() {
var updatetimer = null;
$("#gdimage").mousemove( function( eventObj ) {
clearTimer(updatetimer);
setTimeout(function() { update_hover(eventObj.pageX, eventObj.pageY); }, 500);
}
var update_hover = function(pageX, pageY) {
var location = $("#gdimage").elementlocation();
var x = pageX - location.x;
var y = pageY - location.y;
x = x / 5;
y = y / 5;
x = (Math.floor( x ) + 1);
y = (Math.floor( y ) + 1);
if (y > 1) {
block = (y * 200) - 200;
block = block + x;
} else {
block = x;
}
$("#block").text( block );
$("#x_coords").text( x );
$("#y_coords").text( y );
$.ajax({
type: "GET",
url: "fetch.php",
data: "x=" + x + "&y=" + y + "",
dataType: "json",
async: false,
success: function(data) {
//If you're using Chrome or Firefox+Firebug
//Uncomment the following line to get debugging info
//console.log("Name: "+data.username);
$("#user_name_area").html(data.username);
}
});
});
});
Can you show us the PHP code? Do you use json_encode on the return data?
An alternative would be to simply make the image a background to a <div> container and arrange <a> elements in the <div> where you need them then simply bind with jQuery to their click handler.
This also has benefits if the browser does not support jQuery or javascript as you can actually put the URL you need in the HREF attribute of the anchor. This way if jQuery is not enabled the link will be loaded normally.
A skeleton implementation would look like this:
Example CSS
#imagecontainer {
background-image: url('gd_image.php');
width: 1000px;
height: 1000px;
position: relative;
}
#imagecontainer a {
height: 100px;
width: 100px;
position: absolute;
}
#block1 {
left: 0px;
top: 0px;
}
#block2 {
left: 100px;
top: 0px;
}
Example HTML
<div id="imagecontainer">
</div>
Example jQuery
$(document).ready(function(){
$("#block1").click(function(){ /* do what you need here */ });
});