0

i have two php file , test.php and test2.php
in 'test.php' i have a form and i want to get name and echo it with ajax and php here is my code , what is wrong with it?

test.php

<html>
<head>
<script>
function showHint(str)
{
if (str.length==0)
  {
  document.getElementById("txtHint").innerHTML="";
  return;
  }
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","test2.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>

<p><b>Start typing a name in the input field below:</b></p>
<form method="get">
First name: <input type="text" name="fname">
<input type="submit" value="click me" onclick="showHint(fname)">
</form>
<p>Suggestions: <span id="txtHint"></span></p>

</body>
</html>

and test2.php is

<?php
$q = intval($_GET['q']);
echo $q;
?>
3
  • You're supposed to tell us what's wrong with it, what errors you get or what happens vs what you expect to happen, and what troubleshooting step has you stuck. Commented Feb 21, 2014 at 12:50
  • there is no error , just not working , i mean when i click on button there will be no change in tag <span id="txtHint"> Commented Feb 21, 2014 at 12:54
  • Because you are not returning any parameters through url. You are just printing the value of $q. You can use this value on success though instead of getting the url with .open(). Found it. Check this link. It might help you. stackoverflow.com/questions/4971254/… Commented Feb 21, 2014 at 13:01

1 Answer 1

0

The button in the form is a submission input which will result in the page being reloaded. Add return false to your onclick method to prevent this from happening:

<input type="submit" value="click me" onclick="showHint(fname); return false">

Additionally, your showHint function expects a string but you are passing an HTML input. You can get the text value by adding the following to the top of the function:

if (typeof str !== 'string' && typeof str.value !== 'undefined') {
    str = str.value;
}
Sign up to request clarification or add additional context in comments.

2 Comments

i made this changes, i think it becames better but not completly ok, it prints just '0' (without quet's) , what is wrong?
Your php code forces the output to be an integer as you are using the function intval. You probably want to use htmlspecialchars instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.