0

AJAX only works once, i have to reload the page for it to work again. How do i fix this?

echo "<div class='unsubscribe'><a id='us$id' href='javascript:unsubscribe($id);'><img src='/unsubscribe.jpg' alt='unsubscribe' /></a></div>";



function unsubscribe(number)
{
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
        document.getElementById("us"+number).innerHTML="<img src='/subscribe.jpg' alt='subscribe' />";
    }
  }
xmlhttp.open("GET","/unsubscribe.php?id="+number,true);
xmlhttp.send();
}
Benjamin Crouzier
  • 40,265
  • 44
  • 171
  • 236
user892134
  • 3,078
  • 16
  • 62
  • 128
  • I would recommend learning firebug or chrome developer tools to see what exactly is happening here - you can inspect the network requests, see javascript exceptions, set breakpoints, and step through the code looking for the problem. – lunixbochs Aug 22 '11 at 16:26
  • If you are open to new technilogies, i strongly suggest you to use [jQuery](http://jquery.com/) to make your [ajax calls](http://api.jquery.com/jQuery.get/). It will look like this : `$.get("/unsubscribe.php?id="+number);` – Benjamin Crouzier Aug 23 '11 at 09:22

3 Answers3

0

move the xmlhttp.open("GET","/unsubscribe.php?id="+number,true); before xmlhttp.onreadystatechange=function() line.

here is the ajax order:

  1. open()
  2. onreadystatechange
  3. send()
grepit
  • 21,260
  • 6
  • 105
  • 81
0

Change your HTML : use an onClick handler rather than an href:

<a id='us$id' href="#" onclick="unsubscribe($id);">

This ensures that the action happens on the click, but does not redirect the browser's target page (which is why your function will only fire once at present).

Depending on the layout of your page, you may find the above results in a 'jerk' of the page when the click happens - if so, you can try returning false from the click handler:

<a id='us$id' href="#" onclick="unsubscribe($id); return false;">
Sam Holloway
  • 1,999
  • 15
  • 14
0

I think there is a problem with the names us$id and $id. If you are not using jQuery, then the $ sign is nothing special, it is a plain character. So, us$id and $id are unrelated, $id is just a substring of us$id. So, unsubscribe($id) is called with an undefined argument. If you wanted to replace the image under us$id, then this will not work because getElementById("us"+number) will not find the element.

Jiri Kriz
  • 9,192
  • 3
  • 29
  • 36