refresh div based on link click with data pulled from php file - php

I have an image scroller with a selection of images in it. These images are pulled out of the database. Above the scroller are a list of folders.
When the user click a new folder I want the list of images to update without refreshing the page. I have had a go at making this with ajax but its confusing me a little and is not working at all. Here is what i have got so far
first the default html/php page
the images that are there now a just for test. these will be the default images in no folder when the query is written
About.php
the folders list
<div id="folders">
<ul id="foldername">
<li>test0</li>
<li>test1</li>
<li>test2</li>
</ul>
</div>
then the scroller
<div id="scrolimg">
<img name="" src="" width="150" height="150" alt="" class="singlscrolimg" />
</div>
getImage.php
include('../Connections/dbcon.php');
mysql_select_db($database_dbcon, $dbcon);
$query_rs_image = "SELECT * FROM images WHERE imgfolder='".$_GET['id']."' AND status='1'";
$rs_image = mysql_query($query_rs_image, $dbcon) or die(mysql_error());
$row_rs_image = mysql_fetch_assoc($rs_image);
$totalRows_rs_image = mysql_num_rows($rs_image);
do { ?>
<img name="<?php echo $row_rs_image['imgname']; ?>" src="/images/uploads/<?php echo $row_rs_image['smfile']; ?>" alt="<?php echo $row_rs_image['imgname']; ?>" />
<?php } while ($row_rs_image = mysql_fetch_assoc($rs_image)); ?>
and at the top of about.php
<script>
function getImages(id)
{
$.ajax({
type: "GET",
url: 'getImage.php',
data: "id=" + id,
success: function(data) {
$('#scrolimg').html(data);
}
});
}
</script>

Related

Ajax for changing displayed image in 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

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.

Voting Page using AJAX/JQuery

I am trying to figure this out and I think I am almost there but I am stuck figuring out how to use the variables properly.
I am making a page that allows a user to vote on one of three color M&Ms. By clicking the picture of one of the M&M's on the main html page, your vote will be carried over to a php page using JQuery/AJAX, and the PHP page will then update teh DBase.
My PHP page and Dbase are fine. I am stuck trying to figure out how exactly I can format my HTML page to send over the proper info to my php page so that when the red M&M is clicked, that info will go, the blue, etc etc.
Here are my HTML links:
<div id="red">
<img src="images/red.jpg" width="100%" />
</div>
<div id="blue">
<img src="images/blue.jpg" width="100%" />
</div>
<div id="green">
<img src="images/green.jpg" width="100%" />
</div>
and I want to send these over to my PHP page using JQuery and AJAX to then receive the updated vote counts. How would I formulate the AJAX/jQuery command so that when each link is clicked it sends over the color for that link? I dont need exact code here, just a pointer or two will help.
HTML:
<div id="red" data-color="red" class="answer">
...
</div>
<div id="blue" data-color="green" class="answer">
...
</div>
<div id="green" data-color="blue" class="answer">
...
</div>
JS:
$('.answer').click ( function (e) {
var color = $(this).attr("data-color");
$.ajax({
url: '/your/relative/endpoint',
type: 'POST',
data: '{ color: "'+color+'" }',
success: function (res) {
...
},
error: function (jqXHR) {
...
}
})
})
This will track each color and make the request to your server on click with the appropriate color. Remember that you should sanitize the input server side.
attach a click handler to each of the anchors
in your ajax request send the id of the parent div as a post parameter
Once the request is complete, update the corresponding div with the count from the result
Nick's answer is good just thought I would give you one more option:
<div id="red">
<a href="/vote.php?color=red" class='vote'><img src="images/red.jpg" width="100%" /></a>
</div>
<div id="blue">
<a href="/vote.php?color=blue" class='vote'><img src="images/blue.jpg" width="100%" /></a>
</div>
<div id="green">
<a href="/vote.php?color=green" class='vote'><img src="images/green.jpg" width="100%" /></a>
</div>
Javascript / jquery:
$('.vote').click(function() {
$.ajax({
type: 'POST',
url: $(this).attr('href'),
cache: false,
success: function(resp){
}
});
return false;
});
Is simple.
/****** JQUERY *******/
/**
* SEND NEW VOTE
* #param int color id of color
*/
function SendVote(color){
var count = '';
if( color == 1){
count = 'red';
}
if( color == 2){
count == 'blue';
}
if( color == 3){
count == 'green';
}
//send data via ajax,
var queryParams = {'color':color};
$.ajax({
data: queryParams,
type: "post",
url: 'path/to/vote.php'
beforeSend: function(){ // here you could add a loader (if you want)
//show loader
},
success: function(response){ // success here you get the response from the server
//response is not empty
if( response.length > 0){
$("#"+count+' span').html(response+' votes'); // then change the number of the counter
}else{
//and error on php, cause there response but is empty
}
},
fail: function(e){ //get fail ajax errors
console.log('fail '+e);
},
error: function(e){ // get errors
console.log('error '+e);
}
});
}
/*** ON vote.php (or your php script) *****/
if( isset($_POST['color']) ){
//do the things to add the new vote
//then echo the total of votes for the color
echo getVotes($_POST['color']); //this is the response that ajax will get
}
/********** html *******/
<div id="red">
<img src="images/red.jpg" width="100%" />
<span>
5 votes
</span>
</div>
<div id="blue">
<img src="images/blue.jpg" width="100%" />
<span>
4 votes
</span>
</div>
<div id="green">
<img src="images/green.jpg" width="100%" />
<span>
0 votes
</span>
</div>

How to integrate AJAX to avoid page redirection of PHP CMS

I have used a CMS built with PHP and MySQL. It works great and I have fully customized it to my liking. The only thing now to do is make a more efficient way of loading the data. When a user wants to select an article I want the browser to stay on the same exact page/url without reloading or redirecting. Here is a demo of the CMS: DEMO LINK
For example, the above line of code was exerted from the homepage.php script. It is an anchor tag for the user to select to view the whole content of a particular article, which was only partially displayed in the homepage. When this link is clicked, the user is directed away from the homepage and taken to the article's specific URL. How can I get the full article content page to load inside of the homepage and hide the original homepage content to avoid the page redirect problem. Is this something that can be done with this particular CMS? I can provide any PHP script from the CMS if needed. Thanks in advance.
ARCHIVE.php SCRIPT:
<?php foreach ( $results['articles'] as $article ) { ?>
<li>
<h2>
<span class="pubDate"><?php echo date('j F Y', $article->publicationDate)?></span><br><?php echo htmlspecialchars( $article->title )?>
</h2>
<p class="summary">
<?php if ( $imagePath = $article->getImagePath( IMG_TYPE_THUMB ) ) { ?>
<a href=".?action=viewArticle&articleId=<?php echo $article->id?>">
<div class="floated_child0" style="background-repeat:none; background-image:url('<?php echo $imagePath?>');"></div></a>
<?php } ?>
<?php echo htmlspecialchars( $article->summary )?> (more)
</p>
</li>
<?php } ?>
If you can get the content of the article using ajax and put that content below that title of that article, for ex let say you have a php function in backend which you can call to get the content of article given the article id then you can make a GET ajax request to get the article content and put in the desired div. something like:
<script language="javascript">
$("#view_more").click(function(){
var dataString = "id="+article_ID;
$.ajax({
type: "GET",
url: 'http://myhost.com/articles/getArticleContent',
data: dataString,
success: function(response) {
$('div #description').html(response);
}
});
return false;
});
</script>
update:27-11-2012
you can try something like this, if that helps you understanding better. it may not be exactly what you want but I hope it will help you understanding how you can proceed.
<?php foreach ( $results['articles'] as $article ) { ?>
<li>
<h2>
<span class="pubDate"><?php echo date('j F Y', $article->publicationDate)?></span><br><?php echo htmlspecialchars( $article->title )?>
</h2>
<p class="summary" id="<?php echo $article->id?>">
<?php if ( $imagePath = $article->getImagePath( IMG_TYPE_THUMB ) ) { ?>
<a href=".?action=viewArticle&articleId=<?php echo $article->id?>">
<div class="floated_child0" style="background-repeat:none; background-image:url('<?php echo $imagePath?>');"></div></a>
<?php } ?>
<?php echo htmlspecialchars( $article->summary )?> (more)
</p>
</li>
<?php } ?>
<script language="javascript">
function viewFullArticle(article_ID){
var dataString = "id="+article_ID;
$.ajax({
type: "GET",
url: 'http://myhost.com/articles/getArticleContent',
data: dataString,
success: function(response) {
$('p #'+article_ID).html(response); //assuming response is everything you want to display within summary paragraph
}
});
return false;
};
</script>

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