0
<script type="text/javascript">
document.getElementById('s1').onclick=function()
{
var value1 = document.getElementById('input').value;
var aj;
if(window.ActiveXObject)
{
    aj=new ActiveXObject("Microsoft.XMLHTTP");
}
if(window.XMLHttpRequest)
{
    aj=new XMLHttpRequest();
}
aj.onreadystatechange=function()
{
    if(aj.readyState==4 && aj.status==200)
    {

        document.getElementById("output").innerHTML=aj.responseText;
    }
}
aj.open("GET","tstprinajax.php?name="+value1,true);
aj.send();
}
</script>

This is not working for me. I want to fetch value of one text box and print to a div name "output" with a click of button with AJAX.

HTML code:

<body>
<form action="">
<input type="text" id="input" />
<button id="s1"></button>
<div id="output"></div>
</form>
</body>

tstprinajax.php:

<?php
$q = $_GET["name"];
print "<font size='+6' color='#FF0000'>$q</font>";
?>
pb2q
  • 58,613
  • 19
  • 146
  • 147
BhhooHD
  • 9
  • 6

1 Answers1

0

I suspect your problem is that the page is getting refreshed, because the default type of a button element is submit, and so the form containing the button is being submitted (to the same page). Change your button element to:

<button id="s1" type="button"></button>

If I hardcode the server response (since JSBin doesn't let me actually do server-side handling, and fair enough), making that change makes your code work:

Live Example | Source

In contrast, without the type="button", you get a page refresh instead: Live Example

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • @VishavdeepSingh: It should do, I've replicated both the problem and the solution successfully, see the edit. – T.J. Crowder Mar 29 '13 at 17:18
  • what ever i type in text box it prints "the response". but i want to print what i type. @T.J. Crowder – BhhooHD Mar 29 '13 at 17:29
  • @VishavdeepSingh: Of course it does, as I said, I hardcoded the response. But provided your PHP works, adding `type="button"` to the `button` element should make the text show up. – T.J. Crowder Mar 29 '13 at 17:50