PDA

View Full Version : Update div when click on a image



fercho07
21 Aug 2007, 6:04 AM
Hi, i want to do something but i feel a little bit lost. For example, i have a page with 2 divs. In one div, there are thumbnails of images, the other div is empty until i click on a thumbnail and the image appear in the other div showing it's real size. So, every time i click on a thumbnail, the other div is refreshed.

Any idea in the way to resolve this ? I want just a idea to start. I think one that when an image was click, and id is send to the server by json data. Then, the server response in json and the div get that response to refresh. I have that idea, but i don't know where to start. How can i know which image was clicked if i don't know previously them.

example.htm


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<link rel="stylesheet" type="text/css" href="js/ext-1.1/resources/css/ext-all.css">
<link id="theme" rel="stylesheet" type="text/css" href="js/ext-1.1/resources/css/xtheme-default.css">
<script type="text/javascript" src="js/ext-1.1/adapter/ext/ext-base.js"></script>
<script type="text/javascript" src="js/ext-1.1/ext-all-debug.js"></script>
<script type="text/javascript" src="example.js"></script>
</head>
<body>
<div id="image" style="border: 1px solid black">hola</div>
<div id="thumbs" style="border: 1px solid black">thumbs</div>
</body>
</html>



example.js


Ext.onReady(function() {
Ext.get('thumbs').on('click', function(){
Ext.Msg.alert("MSG","You clicked the button");
});
});


the javascript do nothing, but shows that extjs is working :D

Any idea guys ??

BernardChhun
21 Aug 2007, 6:19 AM
you got the right way to do it dude.

let me clear some points out for you:

1. the thumbnails in the first div will need to have unique IDs so that you know what full image you need to fetch back. You don't necessarily need an Id, it could be any attributes.

2. use event delegation on the image container.

3. detect on what image the user has clicked

4. make the call to get the full image

5. once the server answers, update the second div

here's some sample code.


Ext.fly("image").on("click",
function(e){
var imgId = e.getTarget().id; // assuming you have used unique IDs for your thumbnails
if (!imgId){return false;} // just in case the user didn't click on the image but did click in the image container.
// make the XHR call specifying the ID so that your server side fetches the right full image
var params = Ext.urlEncode({"imageId" : imgId}); // building up the parameters
Ext.Ajax.request({
"url": "whatever.php"
, "method": "POST"
, "params": params
, "success" : function(e){
// when your server side answers back correctly, you may update the second div
var response = eval(["(", e.responseText ,")"].join("")); // eval the answer you get back from your serverside
// build the html
var html = "" // you may use a DomHelper here or build it by hand
Ext.fly("thumbs").update(html);
}
, "failure" : function(e){/* failure function. show an error message */}
, "scope": this
}
);
}, this, true);

Nullity
21 Aug 2007, 6:35 AM
Well, this could get a bit involved, but I can help you get started. First of all, it will be easiest if your images have similar names (this will save you an XHR call for each click). For example, 'car1_thumb.jpg' for the thumbnail and 'car1.jpg' for the full sized image.

Your event handler was close, try something like this:


Ext.get('thumbs').on('click', function(e) {
var el = e.getTarget();
var imgSource = el.src.replace(/_thumb/i, '');
Ext.get('image').dom.innerHTML = "<img src='" + imgSource + "'>";
}, this);


EDIT: Bernard beat me to it.

BernardChhun
21 Aug 2007, 6:52 AM
EDIT: Bernard beat me to it.

yea but I do agree on the fact that the XHR call might be useless here :))

fercho07
21 Aug 2007, 7:53 AM
Guys, thank you a lot for your help. I was learning a lot.

Nullity: i tried your code and is working great.

BernardChhun: now i'm trying your code. despite the code of Nullity is working, i would like to use XHR because in the real aplication that i will put this, the thumbnails will be generated dinamicaly and the full image either so it's more eficient to do it like this.

So, here is the code:

example.htm


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<link rel="stylesheet" type="text/css" href="js/ext-1.1/resources/css/ext-all.css">
<link id="theme" rel="stylesheet" type="text/css" href="js/ext-1.1/resources/css/xtheme-default.css">
<script type="text/javascript" src="js/ext-1.1/adapter/ext/ext-base.js"></script>
<script type="text/javascript" src="js/ext-1.1/ext-all-debug.js"></script>
<script type="text/javascript" src="example2.js"></script>
</head>
<body>
<div id="image" style="border: 1px solid black"></div>
<div id="thumbs" style="border: 1px solid black">
<img id='1' border='0' src='images/test/1.jpg' width='117' height='77'>
<img id='2' border='0' src='images/test/2.jpg' width='117' height='77'>
<img id='3' border='0' src='images/test/3.jpg' width='117' height='77'>
</div>
</body>
</html>
example2.js


Ext.onReady(function() {
Ext.fly("thumbs").on("click", function(e){
var imgId = e.getTarget().id;
if (!imgId){return false;} // if i click in the div container, i receive their id 'thumbs'
// make the XHR call specifying the ID so that your server side fetches the right full image
var params = Ext.urlEncode({"imageId" : imgId}); // building up the parameters
Ext.Ajax.request({
"url": "example.php"
, "method": "POST"
, "params": params
, "success" : function(e){
// when your server side answers back correctly, you may update the second div
var response = eval(["(", e.responseText ,")"].join("")); // eval the answer you get back from your serverside
// build the html
var html = "<img src='images/test/" + idImage + ".jpg' width='430' height='300'>" // you may use a DomHelper here or build it by hand
Ext.fly("image").update(html);
}
, "failure" : function(e){/* failure function. show an error message */}
, "scope": this
}
);
}, this, true);
});
example.php


<?php
$myData = array('idImage' => '2', 'success' => 'TODO OK');
echo json_encode($myData);
?>
Ok, and here my doubts:

* How can i get the response of the server ? i don't understand the eval(). How can i use the idImage from the response ?
{"idImage":"2","success":"TODO OK"}

* if i click in the div container, i receive their id = 'thumbs' and continue processing. How can i ignore that case ?

* wich is the difference between Ext.get and Ext.fly ?

Thanks for your help guys and sorry for my english.

BernardChhun
21 Aug 2007, 9:48 AM
* How can i get the response of the server ? i don't understand the eval(). How can i use the idImage from the response ?
{"idImage":"2","success":"TODO OK"}


the e.responseText line is what your server answered back. You need to eval() it so that the JSON you received is transformed into a Javascript object.
In your case, this line would be possible:

alert(response.idImage);

I was only using the image Id as an example. You need to send back the appropriate data to your client side.



* if i click in the div container, i receive their id = 'thumbs' and continue processing. How can i ignore that case ?


this would do it.

if (imgId == "thumbs"){return false;}



* wich is the difference between Ext.get and Ext.fly ?


At first view, it returns the same thing. but the Ext.fly function returns a flyweight (http://en.wikipedia.org/wiki/Flyweight_pattern) element. In short, that means less memory footprint and improved performance. I use it often for single tasked matters like adding listeners.

fercho07
21 Aug 2007, 4:00 PM
Thanks for all guys. Now is working but i still have some doubts.

example.php


<?php
$id = $_POST["imageId"];
if ($id == 1) {
$myData = array(success => false, msg => 'No se encontro la imagen');
} else {
$myData = array(idImage => "$id", success => true);
};
echo json_encode($myData);
?>
As you can see, i genereta an error if the id is equal to 1. But from the client side, i never enter into the failure segment. Why ?


example.js


Ext.onReady(function() {
Ext.fly("thumbs").on("click", function(e){
var imgId = e.getTarget().id;
if (!imgId){return false;}
if (imgId == "thumbs"){return false;}
var params = Ext.urlEncode({"imageId" : imgId});
Ext.Ajax.request({
"url": "example.php"
, "method": "POST"
, "params": params
, "success" : function(e){
var results = Ext.util.JSON.decode(e.responseText);
Ext.MessageBox.alert('MSG','ID:'+results['idImage']);
var html = "<img src='images/test/" + results['idImage'] + ".jpg' width='430' height='300'>"
Ext.fly("image").update(html);
}
, "failure" : function(e){/* failure function. show an error message */
Ext.MessageBox.alert('Error', 'msg failure');
}
, "scope": this
});
}, this, true);
});

And, if example.htm became example.php and there i have a variable, maybe $_GET['number']. How can i added to the params ?


var params = Ext.urlEncode({"imageId" : imgId, "num": $_GET['number']});

Nullity
22 Aug 2007, 7:27 AM
Thanks for all guys. Now is working but i still have some doubts.

As you can see, i genereta an error if the id is equal to 1. But from the client side, i never enter into the failure segment. Why ?


The failure function is only called if the XHR itself fails. In your success function, you will have to do a check for the value of the 'success' variable and act accordingly.

For example:


Ext.onReady(function() {
Ext.fly("thumbs").on("click", function(e){
var imgId = e.getTarget().id;
if (!imgId){return false;}
if (imgId == "thumbs"){return false;}
var params = Ext.urlEncode({"imageId" : imgId});
Ext.Ajax.request({
"url": "example.php"
, "method": "POST"
, "params": params
, "success" : function(e){
var results = Ext.util.JSON.decode(e.responseText);

if (results.success == true) {
Ext.MessageBox.alert('MSG','ID:'+results['idImage']);
var html = "<img src='images/test/" + results['idImage'] + ".jpg' width='430' height='300'>"
Ext.fly("image").update(html);
}
else {
// code for success == false
}
}
, "failure" : function(e){/* failure function. show an error message */
Ext.MessageBox.alert('Error', 'msg failure');
}
, "scope": this
});
}, this, true);
});



And, if example.htm became example.php and there i have a variable, maybe $_GET['number']. How can i added to the params ?


var params = Ext.urlEncode({"imageId" : imgId, "num": $_GET['number']});


You almost had it, but you forgot to wrap the GET variable in PHP tags. Try this (the '=' is a php shortcut for 'print'/'echo'):


var params = Ext.urlEncode({"imageId" : imgId, "num": <?=$_GET['number']?>});

fercho07
22 Aug 2007, 5:03 PM
Is correct to use php tags inside a javascript ?



var params = Ext.urlEncode({"imageId" : imgId, "num": <?=$_GET['number']?>});


Perhaps it is and the problem is that i don't like it yoo much jeje. Is another way to do it ?

Thanks Guys.

fercho07
27 Aug 2007, 12:18 PM
Hola gente, la verdad que por lo que estuve viendo no se puede hacer lo que me sugirieron:



var params = Ext.urlEncode({"imageId" : imgId, "num": <?=$_GET['number']?>});


A alguien se le ocurre alguna otra forma de hacerlo ?

Muchas gracias.

Nullity
27 Aug 2007, 12:59 PM
Is correct to use php tags inside a javascript ?



var params = Ext.urlEncode({"imageId" : imgId, "num": <?=$_GET['number']?>});


Perhaps it is and the problem is that i don't like it yoo much jeje. Is another way to do it ?

Thanks Guys.

Yes, as long as the file is named with a '.php' extension, you can put PHP code/variables anywhere in the document, including within javascript.

fercho07
27 Aug 2007, 3:56 PM
Yes, i understand this. But is this the only way ? I don't want to rename my javascipts files to php. It seems awful, of course, perhaps it is the only way. I'm just asking :-)

Thanks