0

I need to display a query via AJAX and to be able to do that, i have to match the ID of the product. Thus i thought of performing a POST method via AJAX to allow the execution of the query.

Now i would like to do a trigger function for the AJAX such that the information will be shown on the page itself instead of being redirect to another page. How do i go about doing it ? I have added tried various place to add the Onclick function, however nothing seems to work.

Any suggestion ?

Thanks

 echo '<a onclick="showUser('.$row['ID'].')" method = "POST" action= "viewComments.php">Show Comments</a>';

<script>
function showUser(str) {
  if (str=="") {
    document.getElementById("txtHint").innerHTML="";
    return;
  } 
  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("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
  xmlhttp.open("Post","viewComments.php?q="+str,true);
  xmlhttp.send();
}
</script>
Yeo Tze Tian
  • 123
  • 1
  • 2
  • 10
  • You have a function which requires a parameter: `showUser(str)`, but when you call it, you're not providing a value for that parameter. – IMSoP May 17 '14 at 14:15

3 Answers3

1

Remove the 'href=""' from your links. This is how they should look:

<a Onclick="showUser()" >Show Comments</a>

Hope this helps! :)

Edit: This is how I would call "showUser()" with an ID:

echo '<a onclick="showUser('.$row['ID'].')" >Show Comments</a>';
Viktor Svensson
  • 755
  • 3
  • 17
0

I just do not like those onClick() events in the html. It is also not good practice (see Why is using onClick() in HTML a bad practice?)

It would be just better to bind events to html elements in your javascript not your html. Like this:

Html:

<a href="http://echo.jsontest.com/key/value/one/gotIt" id="myLink" >Show Comments</a>

Javascript:

function addEventListener(el, eventName, handler) {
  if (el.addEventListener) {
    el.addEventListener(eventName, handler);
  } else {
    el.attachEvent('on' + eventName, function(){
      handler.call(el);
    });
  }
}

var el = document.getElementById('myLink');
addEventListener(el, 'click', showUser);

Demo: http://jsfiddle.net/dgrCw/1/

Just my two cents...

Community
  • 1
  • 1
MonkeyVoodoo
  • 538
  • 5
  • 17
-1

Try this one.

<a id="showUser">Show Comments</a>

$('#showUser').click(function(){
  //your ajax code goes here
  return false;
});
pratik nagariya
  • 574
  • 5
  • 21