Ajax for changing displayed image in php - php

Currently, if no images have been clicked, I get my selected image like this and it's also what's shown on first page load.
$pictures = Picture::getPictures($album->getId());
$selectedPicture = $pictures[0];
It selects the first picture and display it like this:
<img src="<?php echo $selectedPicture->getOriginalFilePath($user->getId()); ?>" >
I am trying to change the selected image when a user clicks on a different thumbnail because this is just one of many images of an album.
Attempt with a ajax, I'm not really experienced with it so I couldn't get it to work
<script type="text/javascript">
function Func() {
$.ajax({
type: "POST",
url: "RefreshImage.php",
success: function (json) {}, error: function () {}
})
}
</script>
Then the php portion also has something like to create the thumbnails so that a user can clicks on one, it displays the image. But I'm not sure how to do that.
foreach ($pictures as $pic) {
$output.= "<a href='" . $pic->getOriginalFilePath($user->getId()) . "'> <img style='width:120px;height:120px' "
. "src='" . $pic->getThumbnailFilePath($user->getId()) . "'"
. "name='" . $pic->getFileName() . "' "
. "onClick='Func'></a>";
}
RefreshImage.php content
session_start();
$user = $_SESSION['user'];
//$albums = Album::getAlbums($user->getId());
if (isset($_POST["chosenAlbid"])) {
$album_id = $_POST["chosenAlbid"];
$user = $_SESSION['user'];
$album = Album::getAlbumById($user->getId(), $album_id);
$pictures = Picture::getPictures($album->getId());
$selectedPicture = $pictures[1];
}
?>
<div id="imagecontainer">
<div>
<p style="float: left;"><img style="width:500px;height:400px" src="<?php echo $selectedPicture->getOriginalFilePath($user->getId()); ?>" ></p>
<p><span>
<h4> Description</h4>
</span><?php echo $selectedPicture->getDescription() ?></p>
</div>
</div>

If you rewrite your function into jQuery it will be more easy.
From this
function Func() {
$.ajax({
type: "POST",
url: "RefreshImage.php",
success: function (json) {}, error: function () {}
})
}
To jQuery
$('a[data-refresh-img]').click(function(e) {
e.preventDefault(); // block ahref redirect
$('#imagecontainer img').attr('src', $(this).attr('href')); // replace image
);
Then activate function add data-refresh-img attribute on a tag.
And all will work for you.
JSFIDDLE
** UPDATE **
If you need replace any data with image you can do this
<a data-refresh-img href="original_img_path">
<img
title="picture one"
src="thumbnail_img_path" height=50>
<span style="display: none"><?php echo $selectedPicture->getDescription() ?> AAA</span>
</a>
And change function to
$('a[data-refresh-img]').click(function(e) {
e.preventDefault(); // block ahref redirect
$('#imagecontainer img').attr('src', $(this).attr('href')); // replace image
$('#imagecontainer img').attr('title', $(this).find('img').attr('title')); // replace title
$('#imagecontainer span[data-description]').html($(this).find('span').html()); // replace description
});
JSFIDDLE 2

Related

Can't pass value in image tag

hi i am new in php i am tryig to pass value on image click through ajax call but i can not find value on click on that image
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type= "text/javascript">
function getItem()
{
var dataString = "category_id=" +$(".category_id").val();
alert(dataString);
alert(category_id);
$.ajax({
type: "GET",
url: "header.php",
data: dataString,
success:function(data)
{
$("#partyId").html(data);
}
});
}
</script>
</head>
my html code is like this here i am trying get that category id on click of that image but i can not get this id on click on image
<?php
$catarray = array();
$selectcat = "SELECT * FROM category";
$selectcatRes = mysql_query($selectcat);
while($row = mysql_fetch_assoc($selectcatRes))
{
$category_id = $row['category_id'];
$category_nm = $row['category_nm'];
$cat_img = $row['cat_img'];
echo'<div class="col-md-3 col-sm-6 col-xs-6 col-xxs-12 category_id">
<a href="images/product_1.jpg" class="fh5co-figure to-animate image-popup category_id" onclick="getItem();">
<figure>
<img width="500" height="300" src="vraj/_cat_img/thumb/'.$row['cat_img'].'" onclick="getItem();" class="img-responsive category_id">
</figure>
<h3 class="fh5co-figure-lead">'.$category_nm.'</h3>
<p class="fh5co-figure-text"></p>
</a>
</div>';
}
?>
You haven't output the category id anywhere and so it's impossible to retrieve it.
Output it to a data attribute on the div, remove the other category_id classes and then change the click event to delegated like below (removing getItem). Using this you can get the category id when the anchor or image is clicked.
I also changed to pass an object as the ajax data because there is no need to concatenate your own data string.
jsFiddle demo
Updated PHP:
while($row = mysql_fetch_assoc($selectcatRes))
{
$category_id = $row['category_id'];
$category_nm = $row['category_nm'];
$cat_img = $row['cat_img'];
echo'<div class="col-md-3 col-sm-6 col-xs-6 col-xxs-12 category_id" data-category_id="' . htmlspecialchars($category_id) . '">
<a href="images/product_1.jpg" class="fh5co-figure to-animate image-popup">
<figure>
<img width="500" height="300" src="vraj/_cat_img/thumb/'.$row['cat_img'].'" class="img-responsive">
</figure>
<h3 class="fh5co-figure-lead">'.$category_nm.'</h3>
<p class="fh5co-figure-text"></p>
</a>
</div>';
}
Updated JavaScript:
<script type= "text/javascript">
$(document).on('click', '.category_id a.image-popup, .category_id img.img-responsive', function(){
var category_id = $(this).closest('.category_id').data('category_id');
alert(category_id);
$.ajax({
type: "GET",
url: "header.php",
data: { category_id : category_id },
success:function(data)
{
$("#partyId").html(data);
}
});
return false;
});
</script>
There are a few things that don't work.
Your img tag has no value attribute
You never defined a variable called category_id
You have multiple elements with a class called category_id, you should use an id to have a unique selector.
I guess by value you mean the src attribute? This would be .attr('src') and not val(). val() is only used for input fields because they actually have a value attribute to store data.

How to get the id to set a session variable in php

This first part isn't having any issues now.
<?php
session_start();
while($row = $result->fetch_assoc()){
echo "<div id='name' style='margin-top:50px;'><h2>" . $row['name'] . "</h2>";
echo "<a href='nextPage.php'><img class='pic' src='".$row['imageURL']."' data-id='".$row['id']."' height='100px'/></a></div>";
echo "<div id='bio' style='border-bottom:1px solid #000;'><p>" . $row['bio'] . "</p></div>";
}
?>
<script type="text/javascript">
$(document).on('click', '.pic', function(){
var id = $(this).data('id');
$.ajax({
type: 'POST',
url: 'setSession.php',
data: {myId: id}
});
});
</script>
After I click an image I just get php error messages telling me there is an undefined variable. I currently have 'setSession.php' as a separate page, not sure if it's supposed to be or not.
**Next Page**
<?php
session_start();
include("connect.php");
$result = mysqli_query($con, "select * from table");
mysqli_close($con);
?>
<!doctype html>
<html>
<head>
<title></title>
</head>
<body>
<div class="wrapper">
<img src="<?php echo $row['imageURL'];?>" height="200px"/><br/>
<div class="textSection" style="text-align:center;">
<h2><?php echo $row['name'];?></h2>
<p>
<?php echo $row['bio'];?>
</p>
</div>
</div>
</body>
</html>
firstly, you should start session in that page like this.
session_start();
then access the session variable like this.
$_SESSION['your_key_here'];// this will return the value stored in session.
Put data attribute data-id on img tag and change ids into class since ids should be unique like so :
<img class='pic' src='" . $row['imageURL'] . "' data-id='" . $row['id'] . "' height='100px'/></a></div>";
And register click handler to img using its class together with AJAX request to set data id into session variable like so :
$(document).on('click', '.pic', function() {
var id = $(this).data('id'); // get id value from data-id attribute
$.ajax({
type : 'POST',
url : 'setSession.php',
data : {
myId : id
},
success : function(msg) { /* do something here for success request */ }
});
});
Finally. in setSession.php page :
<?php
session_start();
$_SESSION['id'] = $_POST['myId']; // this come from ajax request
echo "something"; // and this will available on ajax success callback
?>

Assign "$Post->ID" to custom id

So, for a post loop, $post->ID is used to get the post id's.
Is there a way to "change" it to a custom "id"?
Here is what I mean by it:
So, I have a page that is passed onto a template via ajax as following:
There is a first php template called "first.php".
In this file, I have a post loop which contains a button:
$id = get_the_ID();
<?php echo '<button type="button" class="rh_show_image" data-post_id="' .$id. '">' ;?>
<?php echo get_post_meta($post->ID, 'rh_image', true); ?>
<?php echo '</button>';?>
This button has data-post_id which contains the post id. When it is clicked, then a second.php is loaded via ajax:
<script>
jQuery(document).ready(function() {
jQuery('.rh_show_image').click(function(e) {
e.preventDefault();
var rh_contact_form_id = jQuery(this).data("post_id");
jQuery.ajax({
type: "GET",
url: "<?php echo admin_url('admin-ajax.php'); ?>",
dataType: 'html',
data: ({ action: 'rh_second_php', rhc_post_id: rh_contact_form_id}),
success: function(data){
jQuery('#rh_iamge_' + rh_contact_form_id).html(data);
},
error: function(data)
{
alert("Error!");
return false;
}
});
});
});
</script>
When the second.php is called, as you can see from the script above, the post_id of the post is saved and parsed onto the template (data: ({ action: 'rh_second_php', rhc_post_id: rh_contact_form_id}),)
Then in the second.php, I have the following:
<!--Show title-->
<?php echo get_the_title($_REQUEST['rhc_post_id']); ?>
<!--Show image-->
<div class="images">
<?php
$I_will_call_you = callme_image();
foreach ($I_will_call_you as $slideshowimage)
{
echo "<img src='{$slideshowimage}' />";
}
?>
</div>
So, essentially, I am using $_REQUEST['rhc_post_id'] instead of $post->ID
Here is the problem
In the image div from the second.php, it does not show any images because it does not recognized the post id from $_REQUEST['rhc_post_id'].
So, is there a way to make it equal between $post->ID and $_REQUEST['rhc_post_id']?
Something like this: $_REQUEST['rhc_post_id'] = $post->ID
Thanks guys!
EDIT: The image div works fine when it is placed with a post loop, instead via ajax. So, the code itself works fine.
Edit 2: Syntax in the second.php is fixed now

Using jQuery function in a php while loop

I'm having trouble with a jQuery script for voting on posts. I have a "frontpage" with a list of posts from a mysql db. On each post there is a little votebox you can either vote up or down.
jQuery/ajax script:
<script type="text/javascript">
$(document).ready(function() {
$('.plus-button').click(function(){
var postid = <?php echo $postloopid; ?>;
$('.minus-button').removeClass('disliked');
$(this).toggleClass('liked');
alert(postid);
$.ajax({
type:"POST",
url:"php/votesystem.php",
dataType : 'html',
data:'act=like&postid='+postid,
success: function(data){
$('.plus-button').html(data);
}
});
});
$('.minus-button').click(function(){
var postid = $(this).attr('id');
$('.plus-button').removeClass('liked');
$(this).toggleClass('disliked');
$.ajax({
type:"POST",
url:"php/votesystem.php",
dataType : 'html',
data:'act=dislike&postid='+postid,
success: function(data){
$('.minus-button').html(data);
}
});
});
});
</script>
Votebox.php
<?php
// If postid is from frontpage use $postloopid as $postid
if(isset($postloopid)){
$postid = $postloopid;
}
$postid = htmlentities($postid, ENT_QUOTES);;
include("connect.php");
//For test purposes
echo $postid;
// If user logged in show votebox
if(isset($_SESSION['username'])){
$userid = $_SESSION['userid'];
$sql2 = mysqli_query($connect,"SELECT * FROM posts WHERE id='$postid' AND deleted=0");
if($sql2){
$voterow = mysqli_fetch_assoc($sql2);
$checkupvote = $voterow['upvoters'];
$checkdownvote = $voterow['downvoters'];
$checkupvote = explode(" ",$checkupvote);
$checkdownvote = explode(" ",$checkdownvote);
if($checkupvote = array_search($userid,$checkupvote) == true){
echo '<div class="plus-button liked" name="like">+ ' . $voterow['totalupvotes'] . '</div>';
echo '<div class="minus-button" name="dislike">- ' . $voterow['totaldownvotes'] . '</div>';
}
elseif($checkdownvote = array_search($userid,$checkdownvote) == true){
echo '<div class="plus-button" name="like">+ ' . $voterow['totalupvotes'] . '</div>';
echo '<div class="minus-button disliked" name="dislike">- ' . $voterow['totaldownvotes'] . '</div>';
}
else{
echo '<div class="plus-button" name="like">+ ' . $voterow['totalupvotes'] . '</div>';
echo '<div class="minus-button" name="dislike">- ' . $voterow['totaldownvotes'] . '</div>';
}
}
else {
echo 'No result <br />';
}
}
else {
echo 'Cant find user';
}
?>
Frontpage:
<?php
$sql1 = mysqli_query($connect,"SELECT * FROM posts WHERE totalupvotes < $trendmin AND deleted=0 ORDER BY added DESC LIMIT 0,10");
if($sql1){
while($row = mysqli_fetch_array($sql1)){
$postloopid = $row['id'];
?>
<div id="postlist">
<div style="width:400px; font-size:18px; font-weight:bold;">
<a target="_blank" href="post.php?id=<?php echo $row['id']; ?>"><?php echo $row['title']; ?></a>
</div><br />
<article class="slide"><?php echo nl2br($row['post']); ?></article>
<br />
<?php include("php/votebox.php"); ?>
<br />
by <a style="font-size:18px;" href="profile.php?id=<?php echo $row['submittedby']; ?>"><?php echo $row['submitteduser']; ?></a>
at <span style="font-size:12px;"><?php echo $row['added']; ?></span><span style="float:right; margin-right: 10px;"><a target="_blank" href="post.php?id=<?php echo $row['id']; ?>#commentfield"><?php echo $row['totalcomments']; ?> comments</a></span>
</div>
<?php
}
}
?>
The problem now is that when I click the votebox buttons it turns out I only get the postid from the first loaded post from the while loop. Another problem I have is that my total up- and downvotes changes in all the posts on the list, not the specific post.
Any ideas?
The Javascript code isn't in the loop, it can't reference postloopid. Or if it is, you're binding all buttons of the class every time through the loop, and clicking on them will run all the handlers, incrementing all the posts.
You should put the post ID as a data field in the button, and then access that from the Javascript:
echo '<div class="plus-button liked" data-postid="'+$postid+'" name="like">+ ' . $voterow['totalupvotes'] . '</div>';
echo '<div class="minus-button" data-postid="'+$postid+'" name="dislike">- ' . $voterow['totaldownvotes'] . '</div>';
Then your Javascript can do:
$('.plus-button').click(function(){
var postid = $(this).data('postid');
$(this).siblings('.minus-button').removeClass('disliked');
$(this).toggleClass('liked');
alert(postid);
$.ajax({
type:"POST",
url:"php/votesystem.php",
dataType : 'html',
data:'act=like&postid='+postid,
context: this,
success: function(data){
$(this).html(data);
}
});
});
I made the following changes to the JS:
Use $(this).data('postid') to get postid.
Only remove the disliked class from the sibling minus button, not all minus buttons on the page.
Put the returned HTML just in this element, not in all plus buttons. I pass this in the context: parameter, so that the success function can refer to it.
Alright lets go through your jQuery code(just the like function):
Bind click handler to all elements with the class plus-button
$('.plus-button').click(function(){
var postid = <?php echo $postloopid; ?>;
Remove disliked class from all elements with class minus-button
$('.minus-button').removeClass('disliked');
$(this).toggleClass('liked');
alert(postid);
$.ajax({
type:"POST",
url:"php/votesystem.php",
dataType : 'html',
data:'act=like&postid='+postid,
success: function(data){
Set inner html of all elements with class plus-button
$('.plus-button').html(data);
}
});
});
What you want is to store the postid as an attribute on the posts, then use
var postid = $(this).attr('postid')
only remove the disliked class from the current element
$(this)
.parents('{element containing plus and minus button}')
.find('.minus-button')
.removeClass('disliked')
;
store reference to the clicked element
var $this = $(this); // Cool guys do this right in the beginning and use only this variable instead of $(this)
then in your ajax success handler you want to set only the html of the button you clicked, so you may use the reference you stored in the parent function scope
$this.html(data);
EDIT in regards to infinite scroll script
When parts of your page are dynamic, you want to bind the click handler to a static parent element of the dynamic content using:
$("#postsParent").on('click', '.plus-button', function () {/*handler*/})

Jquery, ajax and php

I have this code to present images:
<?php foreach ($images as $row) : ?>
<div class="box col_3">
<p><a href="<?php echo base_url() ?>public/images/fullscreen/<?php echo $row['image'] ?>" rel="prettyPhoto[gallery1]" title="<?php echo $row['title'] ?>">
<img src="<?php echo base_url() ?>public/images/thumbnails/<?php echo $row['image_thumb'] ?>" title="<?php echo $row['title'] ?>" ></a></p>
<textarea name="title_image" rows="3" class="title_image"><?php echo $row['title'] ?></textarea>
<input type="hidden" class="id_image" class="id_image" value="<?php echo $row['id_image'] ?>" >
<input type="submit" name="update_image" id="update_image" value="Update" class="submit" /><br>
Delete image
</div>
<?php endforeach; ?>
User can upload an image, and for every image div with class of box is created.
This is the code which sends data for update.
$(function(){
$('.submit').click(function(){
('.box').append('<img src="<?php echo IMG ?>loadinfo.net.gif" id="loading" />');
var id = $('.id_image').val();
var title = $('.title_image').val();
$.ajax({
url: "<?php echo site_url('gallery/update_image') ?>",
type: 'POST',
data: 'id=' + id + '&title=' + title,
success: function(){
$('#loading').fadeOut(500, function(){
$(this).remove();
});
}
});
return false;
});
});
This works just for the first box, and for the rest it doesn't. What I need to do to make it work?
you are referencing css classes within your javascript
$('.id_image').val()
this will always return the value of the first appearance of this class e.g. the first image.
try to traverse through the DOM using your submit button as start
e.g.
$('.submit').click(function(){
var id = $(this).prevAll('.id_image').val();
this should return the correct value for id.
then you can use the same method to get the title
to update the loading image use the same method, but this time you'll have to use the parents() selector
$(this).parents('.box').append('<img src="<?php echo IMG ?>loadinfo.net.gif" id="loading" />');
as you are now assigning only a single loading image the removal function should work as expected

Categories