Jump to content

Calling ajax from href


Woodburn2006

Recommended Posts

all i have learnt is how to call an ajax function from a form elementbut i want to call it from clicking on an image:

 

i have tried this:

echo "<a href='javascript:showPhoto(aust1001)'><img src='$url' height='65px'></a> ";

 

but get an error saying aust1001 is undefined

 

i basically want this bit of code to call a ajax function rather than reload the whole page

echo "<a href='?id=$photo_id'><img src='$url' height='65px'></a> ";

Link to comment
Share on other sites

all i have learnt is how to call an ajax function from a form elementbut i want to call it from clicking on an image:

 

i have tried this:

echo "<a href='javascript:showPhoto(aust1001)'><img src='$url' height='65px'></a> ";

 

but get an error saying aust1001 is undefined

 

i basically want this bit of code to call a ajax function rather than reload the whole page

echo "<a href='?id=$photo_id'><img src='$url' height='65px'></a> ";

 

A good way to do it, since it appears you're using PHP to populate the smaller images, is to create an array of those images and add an onclick event to each one.  I'm not sure what element contains these images, so my example will use a div with the id of "gallery."

var gallery = document.getElementById('gallery');
var images = gallery.getElementsByTagName('img');

for(var i = 0; i < images.length; i++)
{
   images[i].onclick = function()
   {
      showPhoto(this.id);
   }
}

.
.
.

<div id="gallery">
   <?php
      while($row = mysql_fetch_assoc($result))
      {
         $photo_id = $row['photo_id'];
         $url = $row['url'];
         echo "<img id='$photo_id' src='$url' height='65px' />";
      }
   ?>
</div>

 

I'm assuming that you're pulling the thumbnail info from a database, and that there's more than one image here.

Link to comment
Share on other sites

ok thanks, im not sure i quite understand

 

here is the page im using, im not sure i have linked to the JS properly either so would be good to get it all checked out.

 

this code is a page that is loaded through an include using php. so on my main page there is an area that this page loads into when i click the link on the menu.

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="AJAX/largephoto.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<link href="site.css" rel="stylesheet" type="text/css" />
<style type="text/css">
<!--
body {
margin-left: 0px;
margin-top: 0px;
margin-right: 0px;
margin-bottom: 0px;
background-color: #333333;
}
-->
</style></head>

<body>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td class="spacer_column"> </td>
    <td class="content_sub">
    
<!--start of left sub table -->   

    <table width="100%" border="0" cellpadding="0" cellspacing="0">
      <tr>
        <td colspan="3" class="frame_sub_border_top">galleries</td>
      </tr>
      <tr>
        <td class="frame_border_left_right"> </td>
        <td class="sub_window" align='left'>
    
    <?    
    $sql_galleries = "SELECT gallery,date,photo_id FROM photos ORDER BY date"; 

	$result_galleries = mysql_query($sql_galleries, $connection);
   		if (mysql_error()) { print "Database Error: $sql_news " . mysql_error(); }

	while($row_galleries = mysql_fetch_array($result_galleries)){
		extract($row_galleries);
		$photo_id = substr($photo_id, 0, 5);
		$photo_gallery = $gallery;

		if ($photo_gallery != $current_gallery){
			echo "<img src='images/folder.png' height='30px'> <a href='?go=photos&a=$photo_id'>".$photo_gallery."</a><br / >";
			$current_gallery = $photo_gallery;
		}
	}
	?>
        
          </td>
        <td class="frame_border_left_right"> </td>
      </tr>
      <tr>
        <td colspan="3" class="frame_border_bottom"></td>
      </tr>
      <tr>
        <td colspan="3" class="spacer_row"></td>
      </tr>
      <tr>
        <td colspan="3" class="frame_sub_border_top">where are we?</td>
      </tr>
      <tr>
        <td class="frame_border_left_right"> </td>
        <td class="sub_window"></td>
        <td class="frame_border_left_right"> </td>
      </tr>
      <tr>
        <td colspan="3" class="frame_border_bottom"></td>
      </tr>
    </table>
    
<!--end of left sub table --></td>
    <td class="spacer_column"> </td>
    <td class="content_main_large">
    
<!--start of main content table -->

<table width="100%" border="0" cellpadding="0" cellspacing="0">
  <tr>
    <td colspan="3" class="frame_main_border_top">
    <?
    $sql_gallery_heading = "SELECT gallery FROM photos WHERE photo_id LIKE '$a%'"; 

	$result_gallery_heading = mysql_query($sql_gallery_heading, $connection);
   		if (mysql_error()) { print "Database Error: $sql_gallery_heading " . mysql_error(); }

	$rows_gallery_heading = mysql_fetch_array($result_gallery_heading);

	echo $rows_gallery_heading["gallery"]." (". mysql_num_rows($result_gallery_heading)." photos)";
	?>
    </td>
  </tr>
  <tr>
    <td class="frame_border_left_right"> </td>
    <td class="main_window_photos_thumbs">
      <?
    $sql_thumbs = "SELECT * FROM photos WHERE photo_id LIKE '$a%' ORDER BY photo_id DESC"; 

	$result_thumbs = mysql_query($sql_thumbs, $connection);
   		if (mysql_error()) { print "Database Error: $sql_news " . mysql_error(); }

	while($rows_thumbs = mysql_fetch_array($result_thumbs)){
		extract($rows_thumbs);
		echo "<a href='#' onclick='showPhoto($photo_id)'><img src='$url' height='65'></a>";

	}
	?></td>
    <td class="frame_border_left_right"> </td>
  </tr>
  <tr>
    <td colspan="3" class="frame_border_bottom"></td>
  </tr>
  <tr>
    <td colspan="3" class="spacer_row"></td>
  </tr>
  <tr>
    <td colspan="3" class="frame_main_border_top">large photo</td>
  </tr>
  <tr>
    <td class="frame_border_left_right"> </td>
    <td class="main_window_photos_view">
    <?
if($id==""){echo "<img src='$url' width='660px'>";}
else{
$sql_large_photo = "SELECT url FROM photos WHERE photo_id='$id' LIMIT 1"; 

$result_large_photo = mysql_query($sql_large_photo, $connection);
   	if (mysql_error()) { print "Database Error: $sql_large_photo " . mysql_error(); }

$rows_large_photo = mysql_fetch_array($result_large_photo);
echo "<img src='".$rows_large_photo["url"]."' width='660px'>";}

?>
    </td>
    <td class="frame_border_left_right"> </td>
  </tr>
  
  <tr>
    <td colspan="3" class="frame_border_bottom"></td>
  </tr>
  <tr>
    <td colspan="3" class="spacer_row"> </td>
    </tr>
</table>

<!--end of main content table -->    </td>
    <td class="spacer_column"> </td>
  </tr>
</table>
</body>
</html>

 

when i click on the images in the thumbnail area i get an error saying that the value within the function all is undefined.

 

a working example is: http://travelling.dw20.co.uk/?go=photos

 

there you can see how it is laid out and the error i get

Link to comment
Share on other sites

sure, here it is:

var xmlHttp

function showPhoto(str)
{
xmlHttp=createXmlHttp()
if (xmlHttp==null)
  {
  alert ("Browser does not support HTTP Request")
  return
  } 
var url="largephoto.php"
url=url+"?id="+str
url=url+"&sid="+Math.random()
xmlHttp.onreadystatechange=stateChanged 
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}

 

largephoto.php works fine because i have tested that on multiple occasions

Link to comment
Share on other sites

i put this code after that line but i still got the same error as before,

 

alert (url)

 

is there anything else i can try, like putting the showphoto.js content in the actual php page im calling it from?

 

Write it like:

alert(url);

 

Just to be sure.

 

Putting it in the PHP won't help as the JavaScript is concerned with two things:

1. The actual HTML elements it needs to manipulate

2. The value of the $photo_id

 

Both are available in the HTML file.  No, the error is in the JavaScript itself.  If all the code is stored within AJAX/largephoto.js, then it's not a runtime collision where the script loads before the rest of the document.

 

Change showPhoto to the following:

function showPhoto(str)
{
   alert(str);

   xmlHttp = createXmlHttp()

   if (xmlHttp == null)
   {
      alert("Browser does not support HTTP Request");
      return;
   } 

   var url = "largephoto.php";
   url += "?id=" + str;
   alert(url);
   url += "&sid=" + Math.random();
   alert(url);
   xmlHttp.onreadystatechange = stateChanged;
   xmlHttp.open("GET", url, true)
   xmlHttp.send(null)
}

Link to comment
Share on other sites

no joy still.

 

i get the same error as i always have saying that the value of $photo_id is undefined.

 

could be anything to do with the type of date im feeding?

 

Nah, that shouldn't matter given the way JavaScript handles type.  You could give it a hexadecimal number and it wouldn't care.

 

Is all of your JavaScript within largephoto.js?  Because the error reads like one of those runtime collisions I've mentioned a few times.  If there's any JavaScript within <head>, then stick it all in an onload callback like so:

<head>
   <script type="text/javascript">
      window.onload = function()
      {
         //rest of your non-largephoto.js code
      }
   </script>
</head>

Link to comment
Share on other sites

i have been testing and have got it working here: http://ajaxtesting.dw20.co.uk/photos/

 

but the thing is, it is calling the images from a form which i know how to do but i still cant get it working from a link

 

as you can see from the page it works with the form but not when you click the 'hello' link

 

hopefully this helps

Link to comment
Share on other sites

For your test link, remove the inline onclick call.  Instead, change it to:

<a id="testAjax" href="#">Hello</a>

 

And add the following to the <head> of the document:

<script type="text/javascript">
   window.onload = function()
   {
      var testAjax = document.getElementById('testAjax');

      testAjax.onclick = function()
      {
         showPhoto('aust1001');
      }
   }
</script>

 

It should work with those changes.

Link to comment
Share on other sites

thats works great in the test but i cannot seem to get it working on the actual site, i need a way of getting the photos id passed into the javascript function which i cannt seem to do with this. if you look at http://travelling.dw20.co.uk/?go=photos then you can see.

 

also if i leave the code as you gave it in the head part of the page it will only load the image that is in the call function demand in that script and only a couple of the images work as links

Link to comment
Share on other sites

Okay, first, you created an entirely new html document within the middle of your page.  You can't do this.  HTML doesn't work that way.

 

Second, you need to follow along with what I did.  Remember: I removed the showPhoto() function call from the link.  Sticking it into the id of a link is illogical, and not at all what I did above.

 

On to actual code...

 

At the top of the page, put this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="http://travelling.dw20.co.uk/AJAX/largephoto.js"></script>
<script type="text/javascript">
   window.onload = function()
   {
      var gallery = document.getElementById('gallery');
      var images = gallery.getElementsByTagName('img');

      for(var i = 0; i < images.length; i++)
      {
         images[i].onclick = function()
         {
            showPhoto(this.id);
         }
      }
   }
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<link href="site.css" rel="stylesheet" type="text/css" />
<style type="text/css">
<!--
body {
margin-left: 0px;
margin-top: 0px;
margin-right: 0px;
margin-bottom: 0px;
background-color: #333333;
}
-->
</style></head>

 

REMOVE the following from the middle of your page:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="/AJAX/largephoto.js"></script>
<script type="text/javascript">
var img=null
   window.onload = function(img)
   {
      var testAjax = document.getElementById('testAjax');

      testAjax.onclick = function(img)
      {
         showPhoto('img');
      }
   }
</script>
</head>

<body>

 

Now, give your main content table an id of gallery:

<!--start of main content table -->

<table id="gallery" width="100%" border="0" cellpadding="0" cellspacing="0">

 

Now, here's one of the most important parts.  Redo the line of code that houses the thumbnails so it looks like:

<img id="thai1001" src='http://travelling.dw20.co.uk/images/photos/thai1/thailand.jpg' height='65px'><img id="losa1002" src='http://travelling.dw20.co.uk/images/photos/losa1/la1.jpg' height='65px'><img id="lossa1001" src='http://travelling.dw20.co.uk/images/photos/losa1/la.jpg' height='65px'><img id="lasv1002" src='http://travelling.dw20.co.uk/images/photos/lasv1/vegas2.jpg' height='65px'><img id="lasv1001" src='http://travelling.dw20.co.uk/images/photos/lasv1/vegas1.jpg' height='65px'><img id="fiji1002" src='http://travelling.dw20.co.uk/images/photos/fiji1/FIJI.gif' height='65px'><img id="fiji1001" src='http://travelling.dw20.co.uk/images/photos/fiji1/fiji2.jpg' height='65px'><img id="aust1001" src='http://travelling.dw20.co.uk/images/photos/aust1/aus1.jpg' height='65px'>

 

The ids should be available to you through PHP.  It shouldn't be hard creating the list of images like I have here.

 

That should more or less do it.

Link to comment
Share on other sites

ah sweet, that works a treat.

 

the reason there was a new html doc in the middle is because i have a main page and all the smaller pages like photos etc load within a table on the main page. but thats sorted now so no problem, the only thing is because of this whenever i load up the homepage it comes up with an error saying 'null' is not null or not an object, any ideas?

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.