I have a voting mechanism on the site. When people vote up or down, this code is called:
// Called right away after someone clicks on the vote up link
$('.vote_up').click(function()
{
var problem_id = $(this).attr("data-problem_id");
queue.voteUp = $(this).attr('problem_id');
var span = $(this).closest('span').find('span.votes');
queue.span = span;
vote(problem_id , 1);
//Return false to prevent page navigation
return false;
});
and the vote function that it calls looks like this:
var vote = function(problem_id , vote)
{
if ( vote == 1 )
{
queue.voteUp = problem_id;
}
else
if ( vote == -1 )
{
queue.voteDown = problem_id;
}
var dataString = 'problem_id=' + problem_id + '&vote=' + vote;
// The person is actually logged in so lets have him vote
$.ajax({
type: "POST",
url: "/problems/vote.php",
dataType: "json",
data: dataString,
success: function(data)
{
text = queue.span.text ();
if ( vote == -1 )
{
if ( data == "update_success" )
{
incrementedText = parseInt(text ,10) - 2;
}
else
{
incrementedText = parseInt(text ,10) - 1;
}
}
else
if ( vote == 1 )
{
if ( data == "update_success" )
{
incrementedText = parseInt(text ,10) + 2;
}
else
{
incrementedText = parseInt(text ,10) + 1;
}
}
queue.span.text(incrementedText + " ");
},
error : function(data)
{
errorMessage = data.responseText;
if ( errorMessage == "not_logged_in" )
{
queue.login = false;
//set the current problem id to the one within the dialog
$problemId.val(problem_id);
// Try to create the popup that asks user to log in.
// $dialog.dialog('open');
$("#loginpopup").dialog();
errorMessage = "";
// prevent the default action, e.g., following a link
return false;
}
else
if ( errorMessage == "already_voted" )
{
// Display a dialog box saying that the user already voted
$('<div />').html('You already voted this way on this problem.').dialog();
}
else
if ( errorMessage == "error_getting_vote" )
{
$('<div />').html('Error getting existing votes.').dialog();
}
else
{
// ? :)
}
} // End of error case
}); // Closing AJAX call.
};
and here is the PHP that made the HTML for the vote button. The link is called "important" or "not important" :
echo '<span class="half_text" style="color: #B77F37;">'.$problem_date.'</span>
<span id="votes" class="half_text" style="padding-left: 10px;">'.$vote.'</span>
<strong> <a class="vote_up" style="font-size: 80.0%; color: #295B7B; font-weight:bold; text-decoration:none;" href="#" data-problem_id="'.$problem_id.'">Important</a></strong>
|
<strong><a class="vote_down" style="font-size: 80.0%; color: #295B7B; font-weight:bold; text-decoration:none;" href="#" data-problem_id="'.$problem_id.'">Not Important</a></strong>';
When a user votes, the AJAX gets called, and everything works ok. The only problem is that the HTML does not get updated with the new vote count. Any idea how I can accomplish that?
In your JavaScript you attempt to select the <span id="votes"> using the votes class ($(this).closest('span').find('span.votes');). So I recommend changing:
<span id="votes" class="half_text" style="padding-left: 10px;">
To:
<span class="votes half_text" style="padding-left: 10px;">
I recommend using a parent element to make your selector work properly:
$('.vote_up').click(function() {
console.log($(this).parents('div:first').children('.votes'));
});
//this requires there to be a div element that is the ancestor of the code you posted
Here is a jsfiddle of the above solution: http://jsfiddle.net/jasper/DzZCY/1/
Related
I'm trying to implement a like/dislike button on my page. I managed to get the button to work (it changes like to dislike and vice versa when clicked) and it also creates or deletes the like on the database table. The problem now is the counter of likes. It works only the first time i click the button, i.e. if initially there are 2 likes and i dislike the post the post shows 1 likes, but if I try to click again on it, it keeps showing 1 like and I have to reload the page to see it change to 2 likes.
This is what I have so far:
JQUERY
$(document).on('click', ".miPiace", function() {
trova = '';
commentoORisposta = '';
valCOR = '';
var comOrisp;
try{
trova = $(this).parentsUntil("#fermamiQui");
commentoORisposta = trova.find(".idCommento");
comOrisp = 'commento';
valCOR = commentoORisposta.val();
} catch(err){
trova = $(this).parentsUntil(".infoCommento");
commentoORisposta = trova.find(".idRisposta");
comOrisp = 'risposta';
valCOR = commentoORisposta.val();
}
valCOR = commentoORisposta.val();
if ($(this).hasClass('fa-thumbs-o-up')) {
$(this).removeClass('fa-thumbs-o-up');
$(this).addClass('fa-thumbs-up');
$.get( "lib/ottieniCose.php", { like: "", id: valCOR, comOrisp: comOrisp } )
.done(function( data ) {
trova.find('.numDiLikes').replaceWith('<p>' + data + ' likes</p>');
});
}else if($(this).hasClass('fa-thumbs-up')){
$(this).removeClass('fa-thumbs-up');
$(this).addClass('fa-thumbs-o-up');
$.get( "lib/ottieniCose.php", { remLike: "", id: valCOR, comOrisp: comOrisp } )
.done(function( data ) {
trova.find('.numDiLikes').replaceWith('<p>' + data + ' likes</p>');
});
};
});
PHP
if (isset($_GET['like'])) {
if ($_GET['comOrisp'] == 'commento') {
$commento->set_likes($_GET['id'], true);
return print $commento->get_likes($_GET['id'], true);
} elseif ($_GET['comOrisp'] == 'risposta') {
$commento->set_likes($_GET['id'], false);
return print $commento->get_likes($_GET['id'], false);
}
} elseif (isset($_GET['remLike'])) {
if ($_GET['comOrisp'] == 'commento') {
$commento->remove_likes($_GET['id'], true);
return print $commento->get_likes($_GET['id'], true);
} elseif ($_GET['comOrisp'] == 'risposta') {
$commento->remove_likes($_GET['id'], false);
return print $commento->get_likes($_GET['id'], false);
}
}
Other PHP file where there is the $commenti class
public function get_likes($id, $commento){
$idComm = 0;
$idRisp = 0;
$retVal = ($commento) ? $idComm = $id : $idRisp = $id;
if ($idComm != 0){
$query = "SELECT commento,
(SELECT COUNT(*) FROM likes
WHERE commento = {$idComm})
AS like_count FROM likes";
} elseif($idRisp != 0){
$query = "SELECT risposta,
(SELECT COUNT(*) FROM likes
WHERE risposta = {$idRisp})
AS like_count FROM likes";
}
$trovaQuanti = mysqli_query($_SESSION['connessione'], $query);
$trovaDavveroQuanti = mysqli_fetch_assoc($trovaQuanti);
if ($trovaDavveroQuanti == null) {
return '0';
}
return $trovaDavveroQuanti['like_count'];
}
You may want to try a normal $.ajax call. And turn off caching. Sometimes this causes an issue where you need to refresh to see the changes.
$.ajax({
type: 'GET',
cache: false,
url: "lib/ottieniCose.php",
data: { like: "", id: valCOR, comOrisp: comOrisp },
dataType: "html",
success: function(html){
trova.find('.numDiLikes').html('<p>' + data + ' likes</p>');
}
});
i have a pretty basic voting system i have implemented on my site. using the following ajax when a user clicks on the link there vote is added to the database and the vote is updated +1.
this all works fine but i would like to check if the user is logged in before allowing them to vote if there not display an error pop up or redirect to the login page (eventually i will display a lightbox popup asking for them to login or register.
<script type="text/javascript">
$(document).ready(function() {
$(".voteup a").click(function() {
var ID = <?php echo $moviedetails['id'] ?>
//$("#vote").text();
var rating = <?php echo $vote['vote_up'] ?>
var queryString = 'id=' + ID + '&vote=' + rating;
$("#voteup").text (rating + 1);
$.ajax({
type: "POST",
url: "vote_up.php",
data: queryString,
cache: false,
success: function(html) {
$("#votethanks").html('Thanks');
$("#votethanks").slideDown(200).delay(2000).fadeOut(2000);
}
});
});
});
</script>
and vote_up.php
<?php
require_once("header.php");
$data = $_POST['id'];
$updatevote = "UPDATE `vote` SET `vote_up` = vote_up +1 WHERE `movie_id` = '$data'";
mysqli_query($con, $updatevote);
?>
i have tried
if (!(isset($_SESSION['sess_user_id']) && $_SESSION['sess_user_id'] != '')) {
echo "<script>alert('Please login.')</script>";
}
else { //then the javascript
but it just checks the users logged in on page load, if there not it displays the please login error, but i need it to do this onclick of the javascript.
any help appreciated
thanks
lee
You can consider doing the check with PHP in the vote_up.php and check the response in your ajax. Something like this:
$.ajax({
type: "POST",
url: "vote_up.php",
data: queryString,
cache: false,
success: function(result) {
if (result.error) {
alert(result.msg);
} else {
$("#votethanks").html(result.msg);
$("#votethanks").slideDown(200).delay(2000).fadeOut(2000);
}
}
});
in your vote_up.php:
<?php
if (!(isset($_SESSION['sess_user_id']) && $_SESSION['sess_user_id'] != '')) {
// User is not logged in!
$result = array(
'error' => true,
'msg' => 'Please login first!'
);
} else {
// write the needed code to save the vote to db here
$result = array(
'error' => false,
'msg' => 'Thanks!'
);
}
// Return JSON to ajax call
header('Content-type: application/json');
echo json_encode($result);
Why not use your PHP to insert into a authenticated variable, just as you do with vote and ID?
For example:
var authenticated = <?php !(isset($_SESSION['sess_user_id']) && $_SESSION['sess_user_id'] != '') ?>
Note: Completely untested. I just copied and pasted the php code from your "I have tried..."
Does this help?
Add a boolean. Every time the user clicks on the voting, send an ajax call to check if the user is logged in.
$(document).ready(function()
{
$(".voteup a").click(function()
{
var the_user_is_logged_in;
the_user_is_logged_in = checkLoggedIn();
if the_user_is_logged_in{
// do ajax call
}
else{
alert('Please log in!')
}
}
}
function checkLoggedIn(){
$.get('getsession.php', function (data) {
return data;
});
And in getsession.php you should write
<?php
session_start();
print json_encode($_SESSION);
I didn't try the code, but it should work.
This is what worked for me in the end. I am only sharing this to help someone who my encounter the same problem and end up with a migraine.
The ajax script:
<script type="text/javascript">
function review_likes ( addresscommentid )
{ $.ajax( { type : "POST",
async : false,
data : { "txt_sessionid" : addresscommentid },
url : "functions/review_likes.php",
beforeSend: function() {
// checking if user is logged in with beforeSend
<?php if (!(isset($_SESSION['signed_in_uid']) &&
$_SESSION['signed_in_uid']
!= '')) { ?>
$(window.location.href = 'admin/index-signin.php');
<?php } ?>
},
success : function ( sessionid )
{
$('#reviewlikes').removeClass('like-action');
$('#reviewlikes').load(document.URL + ' #reviewlikes');
},
error : function ( xhr )
{
alert( "You are not Logged in" );
}
});
return false;
}
</script>
On the review_likes.php page header:
<?php
$kj_authorizedUsers = "";
$kj_restrictGoTo = "../admin/index.php";
if (!((isset($_SESSION['kj_username'])) &&
(isAuthorized("",$kj_authorizedUsers,
$_SESSION['kj_username'], $_SESSION['kj_authorized'])))) {
$kj_qsChar = "?";
$kj_referrer = $_SERVER['PHP_SELF'];
if (strpos($kj_restrictGoTo, "?")) $kj_qsChar = "&";
if (isset($_SERVER['QUERY_STRING']) && strlen($_SERVER['QUERY_STRING']) > 0)
$kj_referrer .= "?" . $_SERVER['QUERY_STRING'];
$kj_restrictGoTo = $kj_restrictGoTo. $kj_qsChar . "accesscheck=" .
urlencode($MM_referrer);
header("Location: ". $kj_restrictGoTo);
exit;
}
?>
The above code is a bit overkill, but it helps to get the current URL and redirect the user to the requesting page after successful login.
I have a list on my site that has a favorites button associated with each item on the list. I am using an image as the button to click. The PHP for it is:
echo "<img src=\"./images/emptystar.png\" alt=\"favorite\" class=\"favoritebutton\" billid=\"" . $count['id'] ."\" userid=\"". $_SESSION['userid'] ."\" />\n";
I have javascript/jQuery to make an onclick of that image submit an AJAX request to a PHP file.
$(document).ready(function() {
$(".favoritebutton").click(function () {
var billid = $(this).attr("billid");
var userid = $(this).attr("userid");
var ajaxrequest;
var params = "billid=" + billid + "&userid=" + userid;
ajaxrequest.open("POST","./ajaxphp/favorites.php",true);
ajaxrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxrequest.setRequestHeader("Content-length", params.length);
ajaxrequest.setRequestHeader("Connection", "close");
ajaxrequest.send(params);
ajaxrequest.onreadystatechange=function()
{
if (ajaxrequest.readyState===4 && ajaxrequest.status===200)
{
if(ajaxrequest.responseText === "true")
{
if($(this).attr("src") === "./images/emptystar.png")
{
$(this).attr("src","./images/fullstar.png");
}
else
{
$(this).attr("src","./images/emptystar.png");
}
}
}
};
});
});
The php file at ./ajaxphp/favorites.php is the following:
<?php
include("./includes/dbcxnfunction.inc");
$billid = $_POST['billid'];
$userid = $_POST['userid'];
$query = "IF NOT EXISTS (SELECT * FROM favoritebills WHERE userid = '$userid' AND billid = '$billid' )
INSERT INTO favoritebills (userid,billid) VALUES($userid,$billid)
ELSE
DELETE FROM favoritebills WHERE userid = '$userid' and billid = '$billid' ";
$result = mysqli_query(dbcxn('bill'),$query)
or exit("Couldn't execute query for favorites");
if($result)
{
$request = "true";
}
else
{
$request = "false";
}
echo $request;
?>
In particular I am concerned with the SQL query and the javascript because I am not certain of their correctness, but I used a validator for the javascript with JQuery and everything is valid.
When I click the image on the page, nothing happens even though I have tested both conditions for the image change. Either the javascript is written incorrectly, or there is never a response sent back from the favorites.php file.
The network tab in console.
Use JQuery's .ajax and pass the clicked element by storing it in var before you make the ajax call
$(".favoritebutton").click(function () {
//Store $(this) in var so that it can be passed inside the success function
var this$ = $(this);
var billid = this$.attr("billid");
var userid = this$.attr("userid");
$.ajax( { url : "./ajaxphp/favorites.php", type: 'post', data : { billid : billid , userid : userid },
success : function( responseText ){
if( responseText == "true"){
if( this$.attr("src") == "./images/emptystar.png"){
this$.attr("src","./images/fullstar.png");
}else{
this$.attr("src","./images/emptystar.png");
}
}
},
error : function( e ){
alert( ' Error : ' + e );
}
});
});
I have a functional pagination I built but I now have an issue where the amount of data returned is making the pagination large. I have read through a lot of posts about this issue and havent found anything that was decently close to what I thought I needed. I am looking for my pagination bar to limit the pages. Prev 1 2 3 4 5 6 . . . 11 Next Prev 1 . . . 6 7 8 9 10 11 Next
Jquery
$(function() { //Manage Users Table and Search form JS Start
//loads table page 1 upon loading page.
load_table(1);
/*$("#users_table").tablesorter({
debug: true
}); */
//upon search being clicked the table loads at the first page of result set.
$('#user_search_btn').click(function() {
load_table(1);
});
//global var for the clicking of pages and prev and next buttons.
var page = 1;
$('a.page_link').live('click', function() { //gets the number assigned to the data-page and puts it in page var. load table for page
page = $(this).data('page');
load_table(page);
});
$('#prev').live('click', function() {
//truthy loads page 1 if page - 1 equals 0. falsey loads page - 1.
if(page - 1 == 0) {
page = page;
$('#prev a').removeAttr('href');
}
else {
page = page - 1;
load_table(page);
}
});
$('#next').live('click', function() {
//truthy loads page at its current num which is also max_page
if(page + 1 > max_pages) {
page = page;
$('#next a').removeAttr('href');
}
//falsey loads page if hasnt hit max limit yet + 1
else {
page = page + 1;
load_table(page);
}
});
});
//sets gloabl var to use in multiple functions.
var max_pages = null;
function load_table(page_num) { //function to load the table with data from the providers page. passing a page_num for ajax call reuse.
var search_name = $('#user_name_input').val();
var search_email = $('#user_email_input').val();
var search_company = $('#manage_company_input').val();
var admin_option = $('#admin_user_dropdown option:selected').val();
var active_option = $('#active_user_dropdown option:selected').text();
var page_option = $('#page_limit_dropdown option:selected').val();
$.ajax({
type: 'POST',
url: 'providers/manage_users.php',
data: {mode: 'table_data', company: search_company, name: search_name, email: search_email, admin: admin_option, active: active_option, page_limit: page_option, page_num: page_num},
dataType: 'json',
success: function(data) {
if(data.success == true) {
// sets max_pages each to a rounded up number of the total rows divided by the limit.
max_pages = Math.ceil(data.total_rows / page_option);
//clears out previous data in the table and pagination bar
$('#table_body').html('');
$('#pagination_list').html('');
//Cycles through each row of data in the json array and assigns them to vars.
$.each(data.row, function(j, object) {
var group_id = (object.group_id);
var acct_id = (object.acct_id);
var company = (object.company);
var first_name = (object.first_name);
var last_name = (object.last_name);
var name = (first_name + ' ' + last_name);
var email = (object.email);
var city = (object.city);
var admin = (object.admin);
var active = (object.active);
if(active == 1) {
active = 'yes';
}
else {
active = 'no';
}
//sets each row to a single row from json array
row_show(group_id, acct_id, company, name, email, city, admin, active);
});
//checks if only 1 page of data no pagination bar
if(max_pages > 1) {
pagination();
//sets the current page to the active class
$('#page_'+page_num+'').addClass('active');
//makes the previous and next buttons on the bar active class when conditions are met.
if(page_num == 1) {
$('#prev').addClass('active');
}
if(page_num == max_pages) {
$('#next').addClass('active');
}
}
}
}
});
}
function row_show(group_id, acct_id, company, name, email, city, admin, active){ //function to setup the table row and 5 colmuns of data that the ajax call cycles through.
var html = '\
<tr>\
<td><div><a title="'+company+'" id="company_'+group_id+'" href="edit_facility.php?id='+group_id+'">'+company+'</a></div></td>\
<td><div><a title="'+email+'" id="company_'+acct_id+'" href="edit_user.php?id='+acct_id+'">'+email+'</a></div></td>\
<td><div>'+name+'</div></td>\
<td><div>'+city+'</div></td>\
<td><div>'+admin+'</div></td>\
<td><div>'+active+'</div></td>\
</tr>';
//attachs the above data to the table.
$('#table_body').append(html);
}
function pagination() { //function to make the pagination bar
var current_page = 1;
var html = '<li id="prev">‹ Prev</li>';
//loops through each page according to max_pages and gives it a li el and a el
while(max_pages >= current_page) {
html += '<li id="page_'+current_page+'">';
//data-page used later when clicked to get the current page to load in the ajax call.
html += '<a class="page_link" href="#" data-page="'+current_page+'">'+(current_page)+'</a>';
current_page++;
html += '</li>';
}
html += '<li id="next">Next ›</li>';
$('#pagination_list').append(html);
}
HTML
<table id="users_table" class="tablesorter table table-bordered table-condensed">
<thead id="table_head">
<td><strong>Company</strong></td>
<td><strong>Email</strong></td>
<td><strong>Name</strong></td>
<td><strong>City</strong></td>
<td><strong>Role</strong></td>
<td><strong>Active</strong></td>
</thead>
<tbody id="table_body">
</tbody>
</table>
<div id="user_pagination" class="pagination pagination-centered">
<ul id="pagination_list">
</ul>
</div>
CREATE TABLE messages
(
msg_id INT PRIMARY KEY AUTO_INCREMENT,
message TEXT
);
jquery_pagination.js
$(document).ready(function()
{
//Display Loading Image
function Display_Load()
{
$("#loading").fadeIn(900,0);
$("#loading").html("<img src="bigLoader.gif" />");
}
//Hide Loading Image
function Hide_Load()
{
$("#loading").fadeOut('slow');
};
//Default Starting Page Results
$("#pagination li:first")
.css({'color' : '#FF0084'}).css({'border' : 'none'});
Display_Load();
$("#content").load("pagination_data.php?page=1", Hide_Load());
//Pagination Click
$("#pagination li").click(function(){
Display_Load();
//CSS Styles
$("#pagination li")
.css({'border' : 'solid #dddddd 1px'})
.css({'color' : '#0063DC'});
$(this)
.css({'color' : '#FF0084'})
.css({'border' : 'none'});
//Loading Data
var pageNum = this.id;
$("#content").load("pagination_data.php?page=" + pageNum, Hide_Load());
});
});
config.php
<?php
$mysql_hostname = "localhost";
$mysql_user = "username";
$mysql_password = "password";
$mysql_database = "database";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password)
or die("Opps some thing went wrong");
mysql_select_db($mysql_database, $bd)
or die("Opps some thing went wrong");
?>
pagination.php
<?php
include('config.php');
$per_page = 9;
//Calculating no of pages
$sql = "select * from messages";
$result = mysql_query($sql);
$count = mysql_num_rows($result);
$pages = ceil($count/$per_page)
?>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript" src="jquery_pagination.js"></script>
<div id="loading" ></div>
<div id="content" ></div>
<ul id="pagination">
<?php
//Pagination Numbers
for($i=1; $i<=$pages; $i++)
{
echo '<li id="'.$i.'">'.$i.'</li>';
}
?>
</ul>
pagination_data.php
<?php
include('config.php');
$per_page = 9;
if($_GET)
{
$page=$_GET['page'];
}
$start = ($page-1)*$per_page;
$sql = "select * from messages order by msg_id limit $start,$per_page";
$result = mysql_query($sql);
?>
<table width="800px">
<?php
while($row = mysql_fetch_array($result))
{
$msg_id=$row['msg_id'];
$message=$row['message'];
?>
<tr>
<td><?php echo $msg_id; ?></td>
<td><?php echo $message; ?></td>
</tr>
<?php
}
?>
</table>
CSS Code
#loading
{
width: 100%;
position: absolute;
}
li
{
list-style: none;
float: left;
margin-right: 16px;
padding:5px;
border:solid 1px #dddddd;
color:#0063DC;
}
li:hover
{
color:#FF0084;
cursor: pointer;
}
Try this. It should help you.
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 */ });
});