1
function ajaxFunction(id){
  var ajaxRequest;
  var response;
      try{
      // Opera 8.0+, Firefox, Safari
      ajaxRequest = new XMLHttpRequest();
      } catch (e){
      // Internet Explorer Browsers
      try{
      ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
      } catch (e) {
      try{
      ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e){
      alert("Ajax Failed");
      return false;
    }
  }
}
ajaxRequest.onreadystatechange = function(){
  if(ajaxRequest.readyState == 4){
    response = ajaxRequest.responseText;
  }
}
ajaxRequest.open("GET", "http://priest/getpic.php?id="+id, true);
ajaxRequest.send(null);
return response;

}

function lightbox(id) {
var image;
var imageArr;
document.write(image);

image = ajaxFunction(id);
imageArr = image.split('|');

imageSrc = imageArr[0];
imageWidth = imageArr[1];
imageHeight = imageArr[2];

getElementById('lightbox').visibility=visible;
getElementById('lightboximg').src=imageSrc;

if(imageWidth > 700) {getElementById('lightboximg').width=700;}
if(imageHeight > 500) {getElemetnById('lightboximg').height=500;}


}

The problem I'm having is where my code calls the ajaxFunction() into the image variable the ajaxFunction() isn't returning anything into the variable, causing me to get the following error.

Uncaught TypeError: Cannot call method 'split' of undefined lightbox (anonymous function)

Any Help would be greatly Appreciated.

  • This is getting to be on par with "parsing HTML with regex" as far as to how often it gets asked... dupe of http://stackoverflow.com/questions/9286045/get-json-response-var-outside-of-jquery-function, http://stackoverflow.com/questions/562412/return-value-from-function-with-an-ajax-call, and many more. – Paolo Bergantino Mar 08 '12 at 23:46

1 Answers1

1

AJAX stands for Asynchronous JavaScript and XML. The key part here is really the Asynchronous part. What it means is that when you send a request to the server for information, the browser fetches the information in the background without interfering with the display and behavior of the existing page. Because of this, callbacks are huge when it comes to AJAX - you don't know if your server is going to take 500ms or 3s to return the value, so all you can really do is send the request and say "when you're done, I want you to do this". In your current code your server will very rarely have had time to return whatever getpic.php does before you try returning the value to the function. You just have to modify your code so that ajaxFunction can accept a second argument that is a function callback that is then run within the onreadystatechange part of the code.

Paolo Bergantino
  • 480,997
  • 81
  • 517
  • 436
  • Thank You for your time it is greatly appreciated, now you have explained it, it makes total sense and I'm kicking myself in the backside for not realising this before. lol – Courtenay Rogers Mar 09 '12 at 00:00