By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
460,036 Members | 978 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 460,036 IT Pros & Developers. It's quick & easy.

Image through Ajax not loading correctly.

P: 5
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.
Sep 12 '09 #1
Share this Question
Share on Google+
1 Reply


acoder
Expert Mod 15k+
P: 16,027
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.
Sep 14 '09 #2

Post your reply

Sign in to post your reply or Sign up for a free account.