Image through Ajax not loading correctly.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • kout
    New Member
    • Nov 2008
    • 5

    #1

    Image through Ajax not loading correctly.

    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:
    Code:
    var xmlHttp;
    
    function Ajax(data, url, method) {
      try
    	{
    	  xmlHttp = new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari
    	} catch (e) {
    		  try {
    			xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer
    			  } catch (e) {
    				  try{
    					 xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    					  }catch (e){
    						alert("Your browser does not support AJAX!");
    						return false;
    								 }
    							}
    				   }
    	
    	xmlHttp.onreadystatechange = function() {
    		if (method == 'updatePhoto') updatePhoto();
    		if (method == 'getPhotoCount') getPhotoCount();
    	};
    	
    	xmlHttp.open("POST", url, false);
    	
    	xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    	xmlHttp.setRequestHeader("Content-length", data.length);
    	xmlHttp.setRequestHeader("Connection", "close");
    	
    	xmlHttp.send(data);
    }
    
    function updatePhoto() {
    	if (xmlHttp.readyState == 4) {
    		document.getElementById('photoBlock').innerHTML = "<img src='images/" + xmlHttp.responseText+ "' />";
    	}
    }
    
    function getPhotoCount() {
    	if (xmlHttp.readyState == 4) {
    		photoCount = xmlHttp.responseText;
    	}
    }
    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
    Recognized Expert MVP
    • Nov 2006
    • 16032

    #2
    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.

    Comment

    Working...