Welcome Guest, Not a member yet? Register   Sign In
[Solved...but messy] clickable thumbnails to open jQuery gallery with AJAX
#1

[eluser]DiLer[/eluser]
About me
Hi. I'm completely new to CodeIgniter, jQuery and AJAX (javascript in general). Started this monday Smile
I found CodeIgniter because I make little "websites"(tools) for me with PHP as a hobby. Normally I learn stuff like that by learning-by-doing/tutorials but I'm stuck and I have to show some progress very soon and want to know if I'm even heading in the right direction.


The site and what it should look like
It's not really complicated. That's what even more frustrating about it *g*
The website is about furniture stuff you can buy, like lamps, chairs, tables and whatnot. After selecting a categorie you get to a page that is divided in two parts. A left side and a right side.
On the left side you have a lot of thumbnails of all lamps (or chairs/tables, etc.).
On the right side is a big picture of the selected product with more little pictures beside it (different angles of the same product) and a description beneath it. (that's realized with jQuery)
When you click on a thumbnail the whole gallery on the right gets switched with new images of the selected thumbnail. Of course not only the big pictures is changing, but also the small pictures beside the big one and the description underneath it.


What it look like right now
I installed CI and jQuery and it's up and running.
The URL stuff is working (I removed the index.php) and all prototype sites have been made (where you choose your categorie, etc.). I made a database with some test entries and the categories to choose from.
You can navigate from the front page to products and then tables for example and get to the two-part site with the thumbnails.
The thumbnails are working. I load them from the database. To get a nice gallery (the big picture on the right) I use "jQuery Galleryview 3.0". With the right configuration it's exactly what I want and it's working, too.


My Problem
So where is the problem?
I can't get the thumbnails to work the way I want. Let's say you choose "tables" from the categories. You currently get 5 thumbnails of different tables to choose from and on the right side the jQuery gallery with some test images.
I don't know how to change the jQuery gallery according to which thumbnail I click.

What I tested
I first tried normal javascript with an onclick event to change the picture inside the jQuery gallery. The problem is, that I can only change the small pictures next to the big one (where you can see what picture comes next) and jQuery loads the old pictures anyway. The big picture will still cycle through them.
I guess I have to reload the whole gallery so I thought about AJAX. I didn't even know that you can use jQuery to accomplish the AJAX approach but yeah, it makes sense. After some failed tries with .load(), .click() and other things I started almost from scratch.

This is what I have in mind now:
Every thumbnail has an ID (from the database) and an onclick event. Inside onclick is a function that passes this ID as a parameter. The function itself then loads a php site with jQuerys .load() and the ID as its parameter. The php site uses the ID to create the html code I need for the jQuery gallery.

I tried that but can't even get the javascript onclick part to work properly. Error: "missing formal parameter" at function blubb(1). At least the id works.

-------------------------------------------------------------------------

Here is the complete site (without header & footer) divided so it's easier to read:

My non working function (I have no idea how the paramter in here works, sry)
Code:
[removed]
function blubb(portid)
{
   $("#myGallery").load("<?php echo base_url(); ?>test.php", {var:portid})
}
[removed]


The left side with the thumbnails: (please ignore the ">" for <a> and <img>. The forum otherwise removes part of the code. My fault?)
Code:
<div id="thumbs">
  <ul>
    &lt;?php foreach($tische as $tisch)
      {
        echo '<li><a> onclick="function blubb('.$tisch->id.')" href="#'.$tisch->name.'"><img> src="'.base_url().'img/tische/'.$tisch->thumb.'.jpg" alt="'.$tisch->name.'" title="'.$tisch->name.'" /></a></li>'; echo "\n";
      }
    ?&gt;
  </ul>
</div>


The right side with the jQuery gallery: (hard coded) (outer div "content" was created for testing)
Code:
<div id="content">
         <div id="gallery">
              <ul id="myGallery">
                       <li><img id="p1" src="&lt;?php echo base_url(); ?&gt;img/tische/tisch_1_1.jpg" title="Tisch1" /></li>
                       <li><img src="&lt;?php echo base_url(); ?&gt;img/tische/tisch_1_2.jpg" title="Tisch2" /></li>
                       <li><img src="&lt;?php echo base_url(); ?&gt;img/tische/tisch_1_3.jpg" title="Tisch3" /></li>
              </ul>
              <div id="edit" style="margin-left:450px;">
                       <b>Beschreibung:</b><br />
                       Bla Bla Bla
              </div>
         </div>
</div>

DATABASE

The databse for "Tische" looks like this:
id --- name --- description --- thumb --- gallery
1 --- Kids Table --- small table for kids --- table_1_0 --- table_1_1,table_1_2,table_1_3,....

The idea is to use explode() on the last entry and then fill up the list I need for the jQuery gallery (see code above). Good idea?

Example:
Code:
$pic = explode(",",$tisch->gallery);

And then just fill them in like
Code:
<li><img src="&lt;?php echo base_url().'img/tische/'.$pic[1]; ?&gt;.jpg" /></li>
with foreach or something.


---------------------------------------------


The big question
Is that even the right way? Is there an easier solution? And how does it work if I go that way? Smile
Thanks.

best regards
DiLer
#2

[eluser]pickupman[/eluser]
You are definitely on the right track. A few quick notes.

1.) You url doesn't look correct base_url() / test.php What is the name of your controller you are using in CI. Example say it is gallery.
Code:
&lt;?php echo site_url('gallery');?&gt; //Will create link properly

2.) Using .load() and passing a parameter is going to run a GET request which CI doesn't run natively. You could use:
Code:
function blubb(portid)
{
   $("#myGallery").load("&lt;?php echo site_url('gallery'); ?&gt; / + portid"); //Loads http://yoursite/(index.php/)gallery/portid
}

3.) Anytime you will be loading / changing items on the page you will need to use the [url="http://api.jquery.com/live/"]live()[/url] function. This will reattach the click handler for new loaded DOM elements. .click() only attaches itself to elements when the page is loaded.

4.) Add a class your a(nchor) tags for your thumbnails, and remove the onclick event from them. Instead use:
Code:
echo '<li><  a class="thumb_link" title="' . $tisch->id . '" href="#'.$tisch->name.'"><img> src="'.base_url().'img/tische/'.$tisch->thumb.'.jpg" alt="'.$tisch->name.'" title="'.$tisch->name.'" /></a></li>'; echo "\n";

//Javascript
$(".thumb_link").live('click', function(){
  blubb($(this).attr("title")); //Get title attribute from link and pass to blubb() function
});
#3

[eluser]DiLer[/eluser]
Hey pickupman, thanks for your reply. Smile
I almost got it to work before I read your post so my code looks a little bit different know. But let me reply first:

1)
The test.php was only created to test the output. The whole file consist only of the word "result" (yes, I'm really that creative)
But yeah, I put it outside of the CI folder because I don't really know how to integrate it. More on that later.
About site_url()...this will give me the index.php back into my url, right? I used only base_url() so far and added the rest. Is this okay, or is there a better way?


2)
Yes, I looked into that while testing some stuff the last hours. There are two ways to pass variables, one with get and one with post.

Example:
$("#myDiv").load("myScript.php?var=x&var2=y&var3=z")
and
$("#myDiv").load("myScript.php", {var:x, var2:y, var3:z})

After some testing with the GET method I finally got it right with POST:
Code:
function test(tischid)
{
$('#gallery').load('&lt;?php echo base_url(); ?&gt;inc/test.php', {didi:tischid});
}
I renamed blubb to test and changed the portid to tischid. I also changed the name of the variable that gets passed to "didi". (I had problems to distinguish all the variables after some time and it was the first thing that came to my mind ^^)


3)
Hm..I don't really understand the need of that. I only need this, if I change content that has .click() or onclick on it, right?! Because the thumbnails that will be clicked won't change, they stay on the left side. Only the right side, that has the gallery in it will change.

4)
This look really interesting. I tested something similar but always had the problem to address every single <a> element with an unique id.
Is this some kind of trick to store the ID in the title and access it via attr() or is it intended to use it like this? Could I use something from the <li> tag instead? Because it would look weird if some random number pop up when you hover over a thumbnail.

----------------------------------------------------------------

Update what I did in the meantime

As I said in the beginning, it almost works...almost :/
I already posted the code of the function.

The thumbs part looks like this: (again: ignore the ">")
Code:
<div id="thumbs">
  <ul>
    &lt;?php foreach($tische as $tisch)
      {
        echo '<li><a> href="#'.$tisch->name.'" onclick="test('.$tisch->id.')"><img> src="'.base_url().'img/tische/'.$tisch->thumb.'.jpg" alt="'.$tisch->name.'" title="'.$tisch->name.'" /></a></li>'; echo "\n";
      }
    ?&gt;
  </ul>
</div>
I only changed the part with the function. As somebody with almost no experience with javascript it was of course wrong. Now it should be correct.

The gallery part is the same, I didn't change anything.

The test.php file looks like this:
Code:
$didi=$_POST['didi'];
echo $didi;
It just displays the ID that it gets.

THIS WORKS.
When I click on thumbnail number 1 the gallery goes away and there is only a "1". If I click on thumbnail 2 it changes to a "2", etc.
But I don't want the gallery to go away of course, so I copy&pasted; the <div id="myGallery> box to the test.php
Now I have the problem you already mentioned, because the test.php is outside of the application file. But where does it belong? Model folder? And how do I link to that in my function with .load()?

Inside the test.php now that I got the right ID, I still have to connect to the database and get the description and gallery pictures. How should I do this? Like in a normal model with something like
Code:
$query = $this->db->get_where('mytable', array('id' => $id), $limit, $offset);
with $didi instead of $id and a limit of 1 and no offset.

It's all a little bit confusion right now, I hope it makes all sense to you guys.
I'll test some more and come back later. As always any help is appreciated.

Thanks.
regards
DiLer
#4

[eluser]DiLer[/eluser]
I hope it's OK to make double posts.

Problem solved (but need additional work)

It works, but I have to make some improvements. If you have any suggestions, you're welcome to make a post. I post my code for people who are interested in doing similar projects.

Here is what I did:
I integrated the live() part and the code where I use the <a> title attribute to store my ID as mentioned by pickupman.
My previous test.php file is now fully integrated with a controller, model and view.

My URL looks like this:
http://localhost/ci/design/tische

I created a new function for my design controller and called it "test". Test loads a model namend "model_test" to get all data from the ID (more on that later). It then calls the view "view_test" with this data.

I had some linking problems that are now fixed with the right Control-Model-View setup.
Another problem is the jQuery Galleryview that depends on a script loaded only once at the begining inside the header.php. When I click on a thumbnail only the gallery gets changed, but without a page refresh the information in the script is lost. I fixed this by integrating the script inside my view_test.php file. It works, but is a bad solution.

Code

view_tische.php (code changed for forum display. Ignore ">" on <img> and <a>)
Code:
&lt;!-- /* ---------
  Javascript
------------
Gets the ID from the thumbnail (tischid), loads "test" (from Design-controller) and passes the ID (the ID is now called "didi")
*/ --&gt;

function test(tischid)
{
$('#gallery').load('&lt;?php echo base_url(); ?&gt;design/test', {didi:tischid});   //load "test" from design controller with ID
}

&lt;!-- /* ---------
  Thumbnails
------------
A list of every pic from the database table "tische". The class "thumb_link" is important, see jquery part below.
*/--&gt;

<div id="thumbs">
  <ul>
    &lt;?php foreach($tische as $tisch)
      {
        echo '<li><a> class="thumb_link" href="#'.$tisch->name.'" title="'.$tisch->id.'"><img> src="'.base_url().'img/tische/'.$tisch->thumb.'.jpg" alt="'.$tisch->name.'" title="'.$tisch->name.'" /></a></li>'; echo "\n";
      }
    ?&gt;
  </ul>
</div>

&lt;!-- /*------------------
  jQuery Galleryview
------------------
This setup is required by the jQuery Gallery. The id="myGallery" shouldn't be changed, because Galleryview is looking for it.
The first picture needs the "p1" id.
*/ --&gt;

<div id="gallery">
     <ul id="myGallery">
              <li><img id="p1" src="&lt;?php echo base_url(); ?&gt;img/tische/tisch_1_1.jpg" title="Tisch1" /></li>
              <li><img src="&lt;?php echo base_url(); ?&gt;img/tische/tisch_1_2.jpg" title="Tisch2" /></li>
              <li><img src="&lt;?php echo base_url(); ?&gt;img/tische/tisch_1_3.jpg" title="Tisch3" /></li>
     </ul>
     <div id="edit" style="margin-left:450px;">
              <b>Beschreibung:</b><br />
              Bla Bla Bla
     </div>
</div>

&lt;!--  /*----------
  jQuery part
------------
Gives every thumbnail link a click() function with the title attribute as parameter similar to onclick="test(1)"
*/ --&gt;

$(".thumb_link").live('click', function(){
  test($(this).attr("title")); //Get title attribute from link and pass to test() function
});

design.php (the controller for everything. No template,etc. integrated)
Code:
&lt;?php

class Design extends CI_Controller {

//removed index() and tische()

         public function test()
         {
                 $this->load->model('test_model');
                 $data['tisch'] = $this->test_model->getID();
                 $this->load->view('view_test', $data);
         }
}

test_model.php (I guess a normal variable instead of an array makes more sense)
Code:
&lt;?php

class Test_model extends CI_Model {

        function getID() {

                 $id=$_POST['didi'];      // get the ID that is stored in 'didi' and assign it to $id

                 $q = $this->db->get_where('tische', array('id' => $id));   //get the item from the database where the ID matches

                 if($q->num_rows() > 0) {
                        foreach ($q->result() as $row) {          // probably overkill
                            $data[] = $row;
                        }
                 }
                 return $data;

        }
}

view_test.php (creates the HTML code for jQuery Galleryview when thumbnail is clicked)
Code:
&lt;!-- /* ---------------------
  reload Galleryview Config
--------------------------
The config is already implemented in the header, but is only loaded once I guess.
There is definetly a better solution to that. It works, but it is not good.
Maybe something with live() I don't know.
*/ --&gt;

        $(document).ready(function(){         // only loaded at page load?
                $('#myGallery').galleryView({

                        ....                 // just some Galleryview settings

                });
        });

&lt;!-- /* -------------------------
  creating html for Galleryview
------------------------------
Use data from databse to create the list with all pictures and the description.
$tisch[0] because I send an array with only one item in it :/
*/ --&gt;

&lt;?php

$pics = explode(",",$tisch[0]->gallery);            // "gallery" stores all names of pictures seperated with ","

echo '<ul id="myGallery">';
$temp = 'id="p1"';                       // first <img> needs this class
foreach ($pics as $pic)
{
  echo '<li><img> '.$temp.' src="'.base_url().'img/tische/'.$pic.'.jpg" title="'.$tisch[0]->name.'" /></li>';
  $temp = '';                       // overwrite $temp so all the other <img> won't get this class
}

echo '</ul>';
echo '<div id="edit" style="margin-left:450px;">
     Beschreibung:<br />'.$tisch[0]->description.'
     </div>';

?&gt;

No characters remaining! Tongue
if question -> PM OR reply

regards
DiLer




Theme © iAndrew 2016 - Forum software by © MyBB