Click here to Skip to main content
15,894,343 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I am trying to use this code but it will not work. It is meant to be used for AJAX with JS and PHP. This is the client code:

HTML
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function ajax()
{
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("response").innerHTML = xmlhttp.responseText;
    }
  }
var text = document.getElementById("text").value;
xmlhttp.open("GET","server.php?q=" + text, true);
xmlhttp.send();
}
</script>
</head>
<body>

<form>
<input type="text" id="text">
<button  önclick="ajax()">Send</button>
</form>
<p id="response"></p>

</body>
</html>


Server code:

PHP
<?php
$q = $_REQUEST['q'];
echo $q;
?>


I need it to display the text entered in the box when pressing the button using AJAX not any other method. I am going to use this for a live message service. Please help. Thanks.
Posted
Updated 19-Oct-13 5:16am
v2

1 solution

Change your client code to this
HTML
<html>
<head>
<script type="text/javascript">
function ajax()
{
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("response").innerHTML = xmlhttp.responseText;
    }
  }
var text = document.getElementById("text").value;
xmlhttp.open("GET","server.php?q=" + text, true);
xmlhttp.send();
return false;
}
</script>
</head>
<body>
 
<form>
<input type="text" id="text">
<button  onclick="return ajax();">Send</button>
</form>
<p id="response"></p>
 
</body>
</html>


In your code i found your "onclick" spelling method using special character. And you should return false from javascript then use that value in your button click event so that it should post back. I changed your code and tested on my local development server and its working fine.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900