2014-05-17 175 views
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.通過<a href> - PHP

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> 
+0

你有一個函數,需要一個參數:'showUser( str)',但是當你調用它時,你沒有提供該參數的值。 – IMSoP

回答

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>'; 
+0

Svensson。謝謝它確實有幫助。我是否也可以與您覈對,這是我發佈我的價值(ID)的正確方法嗎? –

+0

你是什麼意思?您在隱藏字段中擁有的ID? –

+0

Yeap。那是一個。你怎麼看 ? –

-1

Try this one.

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

$('#showUser').click(function(){ 
    //your ajax code goes here 
    return false; 
}); 
+0

這需要jQuery。他使用常規的JavaScript。 –

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?觸發AJAX功能)

這將只是更好的事件綁定到HTML元素在你的JavaScript不是你的HTML。 像這樣:

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); 

演示:http://jsfiddle.net/dgrCw/1/

只是我的兩分錢......

相關問題