Connecting Tech Pros Worldwide Forums | Help | Site Map

Image through Ajax not loading correctly.

Newbie
 
Join Date: Nov 2008
Posts: 5
#1: Sep 12 '09
Hello. I'm trying to make some kind of image gallery with php and javascript (w/ ajax), but I've run into some problems.

The basic idea is the following: I've got a <span> tag and, when I click a button, the inner html of the tag changes to <img src="x" />. The problem is that, unless the image is small -less than 80kB-, it won't load properly. Some browsers won't display it entirely, some others won't even show it.

The code related to it:
Expand|Select|Wrap|Line Numbers
  1. var xmlHttp;
  2.  
  3. function Ajax(data, url, method) {
  4.   try
  5.     {
  6.       xmlHttp = new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari
  7.     } catch (e) {
  8.           try {
  9.             xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer
  10.               } catch (e) {
  11.                   try{
  12.                      xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
  13.                       }catch (e){
  14.                         alert("Your browser does not support AJAX!");
  15.                         return false;
  16.                                  }
  17.                             }
  18.                    }
  19.  
  20.     xmlHttp.onreadystatechange = function() {
  21.         if (method == 'updatePhoto') updatePhoto();
  22.         if (method == 'getPhotoCount') getPhotoCount();
  23.     };
  24.  
  25.     xmlHttp.open("POST", url, false);
  26.  
  27.     xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  28.     xmlHttp.setRequestHeader("Content-length", data.length);
  29.     xmlHttp.setRequestHeader("Connection", "close");
  30.  
  31.     xmlHttp.send(data);
  32. }
  33.  
  34. function updatePhoto() {
  35.     if (xmlHttp.readyState == 4) {
  36.         document.getElementById('photoBlock').innerHTML = "<img src='images/" + xmlHttp.responseText+ "' />";
  37.     }
  38. }
  39.  
  40. function getPhotoCount() {
  41.     if (xmlHttp.readyState == 4) {
  42.         photoCount = xmlHttp.responseText;
  43.     }
  44. }
The php file just returns the image location within the server. There's a <span> tag with id 'photoBlock' in the main html webpage.

acoder's Avatar
Site Moderator
 
Join Date: Nov 2006
Location: UK
Posts: 14,589
#2: Sep 14 '09

re: Image through Ajax not loading correctly.


You'll probably need to cache the images. If you already know the images that could be displayed, you could perhaps load them before they're required.
Reply


Similar JavaScript / Ajax / DHTML bytes