Query MySql DB on image hover and update page without refreshing - php

I am currently putting together a page where I have a list of 15 staff images. I'm trying to configure this so that when a user hovers over the image, a div in the upper-right corner updates with information queried from a MySql DB. For instance, web user hovers mouse over picture of Staff #112 -> Div updates to include height, weight, location, and position from mysql without refreshing. I have researched for a while but can only find how this is done using Ajax, Php, Jquery, and a form element. Any help, tutorials, or information would be greatly appreciated. Thanks!
UPDATE
I ended up changing some of the code that was provided and the final version was:
<script type="text/javascript">
$('.staff_hover').on('click', function(){
id = $(this).attr('id');
$.post('staff_php.php',{id: id}, function(data) { var obj = jQuery.parseJSON(data);
var staffnum = obj.staffnum;
var height = obj.height;
var eye = obj.eye;
var hair = obj.hair;
var abt1 = obj.abt1;
var abt2 = obj.abt2; alert(obj.height);
$('#staff_info').html('<b>STAFF #</b>: ' + staffnum + ' <br /><b>HEIGHT</b>: ' + height + ' <br /><b>EYE COLOR</b>: ' + eye + '<br /> <b>HAIR COLOR</b>: ' + hair + '<br /><b>ABOUT</b>:<br /> <b>-</b> ' + abt1 + '<br/><b>-</b> ' + abt2);
});
}); </script>

Here is how flow of your application would work with jQuery, PHP,MySQL:
Browser through jQuery would send request to a server.
PHP would receive request do query to MySQL. And return result back.
jQuery would get response and populate div.
So you need PHP script and JavaScript.
Start with PHP and try to get things from db (look in to PHP PDO)
Than look into jQuery.ajax().
Good luck.

You will want a structure something like this:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
$('img').hover(function() {
id = $(this).attr('id');
$.ajax({
type: "POST",
url: "ax_get_staff.php",
data: 'hovered_id='+id,
success:function(data){
alert(data);
var obj = jQuery.parseJSON(data);
var height = obj.height;
var weight = obj.weight;
alert(obj.height);
$('#upper_right_div').html('Height is: ' + height + ' and weight is: ' + weight);
}
});
},function(){
//Hover-out function
//Clear your div, or some such
$('#upper_right_div').html('');
});
});
</script>
</head>
<body>
<div id="myDiv">
Hover over picture below to GO:<br />
<img id="6" src="http://www.gravatar.com/avatar/783e6dfea0dcf458037183bdb333918d?s=32&d=identicon&r=PG">
</div>
<div id="upper_right_div"><div>
</body>
</html>
And your AJAX (ax_get_staff.php) file will look like this:
<?php
include 'login_to_database.php';
$id = $_POST['hovered_id'];
$result = mysql_query("SELECT `height`, `weight`, `location` FROM `staff` WHERE `user_id` = '$id'") or die(mysql_error());
$staff = mysql_fetch_assoc($result);
//print_r($staff);
echo json_encode($staff);
?>

Related

Extract div id to php variable to multiply

I have a script Ajax/jQuery this autoupdate a statistics in my site this is the code:
<!--Jquery/AJAX script-->
<script type="text/javascript">
function updateStats(stat)
{
var stat = ["online","newestPlayer","cuentas","personajes","guilds"];
var url = "template/Next/stats_do.php";
$.each(stat, function(i, key){
$.post(url, {stats: key}, function(data) {
$("#" + key).text(data);
});
});
}
setInterval('updateStats("updateStats")', 500);
</script>
Work all fine. for the results i use. for example...
But i have a ProgressBar with php. The code for work is (a part)
<?= round (HERE MY RESULT*100/$pBar2max); ?>%
The problem is that putting the does not allow multiplication in order to get the percentage
and i try
$onlines = <span id="online">
and insert a echo in the code, but not work, any solutions? i need extract a number in text for multiply with *100

jquery update item count on click when fetching ajax

I have created a ajax load more button to grab more data from my database, which all works fine. I am now trying to do a count, so the button displays how many results are left to display. Here is my jQuery code that is fired when the button is clicked:
jQuery(document).ready(function(){
jQuery(document).on('click','.show_more',function(){
var ID = jQuery(this).attr('id');
var count = jQuery(".singleproduct").length;
var totals = jQuery('.totalleft').text();
var finaltotal = totals - count;
//jQuery('.show_more').hide();
jQuery('.loding').show();
jQuery.ajax({
type:'POST',
async: true,
crossDomain : true,
url:'example.com/data.php',
data:'count='+count,
success:function(html){
//jQuery('#show_more_main'+ID).remove();
jQuery('.retailitems').append(html);
jQuery('html, body').animate({scrollTop: jQuery(".site-info").offset().top}, 1000);
}
});
jQuery( ".totalleft" ).replaceWith( finaltotal );
});
});
And here is the code for the button:
<span id="<?php echo $result['id']; ?>" class="show_more" title="Load more posts">Load <span class="totalleft"><?php echo $loadmore;?></span> more</span>
When clicked for the first time, the button updates with the correct remaining results. When clicked a second time, the news results populate, but the count remains the same.
Do i have things in the right order above?
Thanks
EDIT
So i found the issue. The calculations were correct, but when updating the count on the button i was actually removing the class of 'totalleft' with this:
jQuery( ".totalleft" ).replaceWith( finaltotal );
So i replaced this with:
jQuery( ".totalleft" ).text( finaltotal );
and all is fine, thanks for all the help.
parse the text() in .totalleft to get an integer value
var totals = parseInt(jQuery('.totalleft').text());
if your calculations are correct, you should get the right number back
EDIT
because ajax is async you are re-updating the value of .totalleft before the ajax is complete.
make sure that you are doing that in the ajax callback:
success:function(html){
//jQuery('#show_more_main'+ID).remove();
jQuery('.retailitems').append(html);
jQuery('html, body').animate({scrollTop: jQuery(".site-info").offset().top}, 1000);
jQuery( ".totalleft" ).replaceWith( finaltotal );
}
finally, I'm not sure what var count = jQuery(".singleproduct").length; is so make sure that the values you are expecting are correct by console logging before and after the subtraction
EDIT #2
var count = jQuery(`.singleproduct`).length;
console.log('count :' + count);
var totals = jQuery('.totalleft').text();
console.log('totals :' + totals);
are you getting numbers on the above logs? if not, then you might be replacing some part of your html with the ajax request and singleproduct or totalleft may not be there anymore

Can I nest clicks for ajax calls within previously appended call results?

I'm making some early attempts at educating myself in AJAX and trying to speed pages rather than relying on PHP to show results. I have hit a hurdle.
I essentially have 3 tiers of data. With 3 database tables.
The first tier of data is pulled via a PHP loop and displayed upon page load.
The second tier of data is loaded via AJAX when A is clicked and then appended to the page via jQuery.
The third tier (where I'm having trouble) is loaded via AJAX when the second tier is clicked...and appended within the previously appended B data.
Like so....
<!-- language: lang-html -->
<!-- PHP loop to pull list if Item A data upon page load -->
<p>Item A</p>
<!-- click Item A -> AJAX pull B data and append results to .a-results -->
<div class="a-results">
<p>Item B</p>
<!-- click Item B -> AJAX and append results to .b-results -->
<div class="b-results">
<p>B resultrow</p>
<p>B resultrow</p>
<p>B resultrow</p>
<p>B resultrow</p>
</div>
</div>
Ajax examples:
<!-- language: lang-js -->
$('a.a-call').click( function (e) {
e.preventDefault();
var sid = $(this).attr('data');
$.ajax({
url: 'secondtier.php',
type: 'POST',
dataType: 'json',
data: ({sid: sid}),
success: function(rows) {
for (var i in rows) {
var row = rows[i];
var id = row[0];
var name = row[1];
var type = row[2];
$('.a-result').append("<p><a href='#' id='s"+id+"' data='"+id+"' class='b-call'>id: " + id + " name: " + name + " type: " + type + "</a></p><div class='b-data'></div>");
}
}
});
});
$('a.b-call').click( function (e) {
e.preventDefault();
var bid = $(this).attr('data');
$.ajax({
url: 'thirdtier.php',
type: 'POST',
dataType: 'json',
data: ({bid: bid}),
success: function(rows) {
for (var i in rows) {
var row = rows[i];
var id = row[0];
var data = row[1];
var cost = row[2];
$(this).next('.b-data').append("<p>date: " + date + " cost: " + cost + "</p>");
}
}
});
});
My AJAX calls work in themselves, however I can't get the B call to append results within the A results. The Item B AJAX works just fine if it's hard coded into the HTML, it's only when it's appended that I can't get it work. No console errors anywhere. Just nothing happening on the page.
I'm not totally current on jQuery usage. I tried .live('click', function() for the Item B click, however the console is telling me it's not valid. I assumed jQuery dropped that at some point.
Using google to link to jquery 1.9.1
<!-- language: lang-html -->
<script language="Javascript" type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Am I going about this wrong? Can I get the appended anchor in B to call another ajax function and append more to the previously appended div?
I don't want to load all this data at once. This is my very reason for learning AJAX. The page currently loads everything via PHP and due to the amount of datasets within datasets it's a slow page load. I'm trying to get specific data to only load upon a click.
You need to use delegate() , because .b-call elements does not exist on page load, so jQuery doesnt know where those elements are. So you need to delegate an event to an element that will exist after page load.
$('.a-result').delegate('.b-call','click',function (e) {
e.preventDefault();
var bid = $(this).attr('data');
$.ajax({
url: 'thirdtier.php',
type: 'POST',
dataType: 'json',
data: ({bid: bid}),
success: function(rows) {
for (var i in rows) {
var row = rows[i];
var id = row[0];
var data = row[1];
var cost = row[2];
$(this).next('.b-data').append("<p>date: " + date + " cost: " + cost + "</p>");
}
}
});
});
I think the problem is due to the fact that the link for fetching the B data is created when A is fetched.
The click event handler ($('a.b-call').click) is registered before the actual DOM element exists and therefore it does not get triggered.
To get this event handler working you need to change your code. The a-results div exists on page load, so you can attach the event handler to this element and simply specify the selector for a.b-call:
Example:
$('.a-results').on('click', 'a.b-call', function(e) {
// your B load code here
}

How do I implement Ajax/JQuery to an existing PHP MYSQL pagination script?

Below is a working pagination script that displays content from a MySQL database. I need to have the pages seamlessly load within the container "#content" rather than have the entire page refreshed. I search extensively for hours but none of the tutorials I encountered helped me implement Ajax/JQuery on this script.
Here is the code I use to display my articles + pagination.
<div id="content">
<?php
include('db.php');
$stmt = $db->query('SELECT * FROM db');
$numrows = $stmt->rowCount();
$rowsperpage=21;
$totalpages=ceil($numrows/$rowsperpage);
if(isset($pageid)&&is_numeric($pageid)){$page=$pageid;}else{$page=1;}
if($page>$totalpages){$page = $totalpages;}
if($page<1){$page=1;}
$offset=($page-1)*$rowsperpage;
$stmt=$db->prepare("SELECT * FROM db ORDER BY ID DESC LIMIT ?,?");
$stmt->bindValue(1, "$offset", PDO::PARAM_STR);
$stmt->bindValue(2, "$rowsperpage", PDO::PARAM_STR);
if($stmt->execute()) {
while ($row = $stmt->fetch()) {
echo '
<article>
article here
</article>
';}}
$range=4;
echo'
<div id="pagination">';
if($page>1){
echo "
<a href='http://www.domain.com/1/'><<</a>";
$prevpage = $page - 1;
echo "
<a href='http://www.domain.com/$prevpage/'><</a>";
}
for ($x = ($page - $range); $x < (($page + $range) + 1); $x++) {
if(($x>0)&&($x<= $totalpages)){
if($x==$page){
echo'
<span class="current">'.$x.'</span>';
}
else{echo"<a href='http://www.domain.com/$x/'>$x</a>";}
}
}
if($page!=$totalpages){
$nextpage=$page+1;
echo"
<a href='http://www.domain.com/$nextpage/'>></a>";
echo "
<a href='http://www.domain.com/$totalpages/'>>></a>";
}
echo '
</div>';
?>
Your setup is a little unclear, but bear with me.
I'm going to assume that on the client side you know when to load the next page (ie the user clicks a button or scrolls to the end of the page etc...) I'm also going to assume that the PHP code you've posted is in its own file and outputs only what you've posted in your question (aka it outputs only the HTML for the articles and nothing else, no wrappers, nothing, if not make it so.
What you're going to want to do is use jQuery (From your question it looks like you already have it on your site so adding another library isn't too taboo) to make an AJAX request to this PHP page. The PHP then echos out what you've posted and the jQuery inserts this on the page inside the #content div.
First a note: I wouldn't recommend having your PHP page output the content div, I would recommend having that stay on the client side and only changing the content of it to what your script returns.
To load new content, you can use this javascript function on the client side:
function makePaginationRequest( pagenum = 1 ) {
// Make ajax request
$.ajax("test2.php", {
// Data to send to the PHP page
data: { "pagenum": pagenum },
// Type of data to receive (html)
dataType: 'html',
// What to do if we encounter a problem fetching it
error: function(xhr, text){
alert("Whoops! The request for new content failed");
},
// What to do when this completes succesfully
success: function(pagination) {
$('#content').html(pagination);
}
})
}
You can place any other parameters you need to pass to the server inside the "data" object (the data: { "pagenum": pagenum }, in key-value form. As you can see from the example, you pass the page number to this function and it passes the "pagenum" request variable to the server.
You'll want to implement a better error handler obviously. As well as change the "test2.htm" filename to that of your PHP script.
A better way of doing this
I feel compelled to mention this:
The way above (what you asked for) is really a messy way of doing this. Whenever you request AJAX data from your server, the server should return content, not markup. You should then insert this content into markup on the client side.
To do this, you would modify your PHP script to first put everything in an array (or an array of array for multiple articles) like this:
while ($row = $stmt->fetch()) {
$output_array[] = array(
"post_title" => $row["title"],
"post_date" => $row["date"],
// etc....
);
}
Then echo it like so:
die(json_encode($output_array));
Then modify your json request:
function makePaginationRequest( pagenum = 1 ) {
$.ajax("test2.htm", {
data: { "pagenum": pagenum },
dataType: 'json',
error: function(xhr, text){
alert("Whoops! The request for new content failed");
},
success: function(pagination) {
// Empty the content area
$('#content').empty();
// Insert each item
for ( var i in pagination ) {
var div = $('<article></article>');
div.append('<span class="title">' + pagination[i].post_title + "</span>");
div.append('<span class="date">' + pagination[i].post_date + "</span>");
$('#content').append(div)
}
}
})
}
jQuery will automagically parse this JSON output into a native javascript object for you.
Taking this approach of having the client make the markup takes alot of load off of your server, and requires less bandwith.
Food for thought, hope that helps.
If you want to do the least amount of rewriting to your original script, the jQuery .load() method might be your best bet. You would basically just need to supply an id to the element that contains all of your articles; something like this should work:
<div id="container">
<div id="articles-container">
<article> ... </article>
</div>
</div>
<div id="pagination">
1 ...
</div>
Then add a script tag and some jQuery code:
<script>
$(function(){
$('#pagination').on('click', 'a', function(e){
e.preventDefault();
var url = $(this).attr('href');
$('#container').load(url + ' #articles-container');
});
});
</script>
.load() will fetch the page, and if you add the optional fragment to the URL, it will filter the result to the element matching the fragment.
EDIT:
Okay, so, to make this work with your current pagination, you need to manually swap the elements. So, assuming your generated markup looks something like this:
<div id="pagination">
1
<span class="current">2</span>
3
4
5
</div>
We want this to happen after the load() completes, so we need to add a callback function to it. I'm also adding a self reference to the clicked element, which we need later:
$(function(){
$('#pagination').on('click', 'a', function(e){
e.preventDefault();
var $this = $(this);
var url = $this.attr('href');
$('#container').load(url + ' #articles-container', function(response, status, jqxhr){
});
});
});
Inside the callback is where we start manipulating #pagination. The first part is easy enough:
var $curr = $('#pagination span.current');
var page = $curr.text();
$curr.replaceWith('' + page + '');
Now we need to replace the link we just clicked:
$this.replaceWith('<span class="current">' + $this.text() + '</span>');
Et viola!, your pagination should be updated. Here's the whole update:
$(function(){
$('#pagination').on('click', 'a', function(e){
e.preventDefault();
var $this = $(this);
var url = $this.attr('href');
$('#container').load(url + ' #articles-container', function(response, status, jqxhr){
var $curr = $('#pagination span.current');
var page = $curr.text();
$curr.replaceWith('' + page + '');
$this.replaceWith('<span class="current">' + $this.text() + '</span>');
});
});
});

JQuery: Why is this Load More Functionality not working?

Trying to implement a simple "load more" functionality with jquery. The idea is to use it in the same way as one does pages. Click and a certain number of posts loaded from the database show up.
I have the following javascript:
$(function(){
var count = 0;
var num = 20;
$("#contents").load("posts.php");
$("#more").click(
function(){
var count = 0;
var num = 20;
$("#contents").load("posts.php");
$("#more").click(
function(){
$(".loading").show("fast");
count += num;
$.post("posts.php", {'page': count}, function(data){
$("#contents").append(data);
$(".loading").hide("slow");
});
}
);
and the following file posts.php
<?
echo "hello";
?>
And I have another file page.php with
<div id="contents"></div>
<div class="loading"><span style="text-decoration: blink;">LOADING...!</span></div>
<button id="more">More..</button>
When i click the "More Button" though nothing happens even though I'm just trying to print out a simple hello world here. I have loaded the javascript in the head of the file like
<script type ="text/javascript" src ="javascript/load.js"></script>
Other javascript functionality I've implemented is working fine. Is there something to add to the "loading" or "contents" elements in page.php?
Your javascript lacks basic syntactic structure, and must be issuing a syntax error, unless you messed it up while posting here. Try this:
$(function(){
var count = 0;
$("#more").click(loadPosts);
loadPosts();
function loadPosts() {
var num = 20;
$(".loading").show("fast");
count += num;
$.post("posts.php", {'page': count}, function(data){
$("#contents").append(data);
$(".loading").hide("slow");
});
}
});
UPDATE
Edited the code above and removed $("#contents").load("posts.php");. It was not necessary, and redundant.

Categories