Adnan Zahid
Adnan Zahid

Reputation: 583

Detecting button press using AJAX and PHP

I'm trying to detect whether a button is pressed using AJAX and PHP (ofcourse this is part of a test not my actual aim). I can detect whenever I type something in a textbox but cannot detect whether a button is pressed or not.

<html>
<head>
<script type="text/javascript">
function insert(){

if (window.XMLHttpRequest)
    xmlhttp=new XMLHttpRequest();
else
    xmlhttp=new ActiveXObject('Microsoft.XMLHTTP');

xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
    document.getElementById('adiv').innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open('GET','AJAX.inc.php?search='+document.getElementById('search_text').value+'search_button=Search!', true);
xmlhttp.send();
}
</script>
</head>
<body>
<input type="text" id="search_text" name="search" onkeyup="load();">
<input type="submit" name="search_button" value="Search!">
<div id="adiv"></div>
</body>
</html>

And here's my AJAX file:

<?php
if(isset($_GET['search_button'])){
echo 'You pressed a button!';
}
?>

Upvotes: 0

Views: 358

Answers (1)

Passerby
Passerby

Reputation: 10070

If your button is not in a form, you can simply use <button> or <input type="button">.

You can use <button onclick="insert();">Search!</button> to listener to button press event.

Upvotes: 1

Related Questions