ofnowhere
ofnowhere

Reputation: 1135

Php-javascript code working only once

I have simple code that inserts values to database without page refresh using javascript. The problem is that when I use "onchange" atrribute in method to call the function the code works fine and value is inserted but when i remove "onchange" form and use a Button "onclick" attribute to call same method it works on once and then stops working.

The code of my comment.html file is

 <html>
<head>
<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("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>

<form method="GET">
<input type="text" name="q">
<button method="GET" onclick="showUser(q.value)">Submit</button>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here.</b></div>

</body>
</html>

And the code of my getuser.php file is:

  <?php
$q = intval($_GET['q']);

$con = mysqli_connect('localhost','root','','login');
if (!$con)
  {
  die('Could not connect: ' . mysqli_error($con));
  }

mysqli_select_db($con,"ajax_demo");
$sql2= "INSERT INTO `users` ( `FirstName`) VALUES( '{$_GET['q']}') "; 
$result = mysqli_query($con,$sql2);
while($row = $result)
  {
  echo "<tr>";
  echo "<td>" . $row['FirstName'] . "</td>";
  echo "</tr>";
  }
echo "</table>";

mysqli_close($con);
?>

Upvotes: 1

Views: 209

Answers (2)

davidkonrad
davidkonrad

Reputation: 85518

@Lavneet is in right direction, but does not solve the problem.

If you insist of that setup you must return false in the onclick :

<button onclick="showUser(q.value);return false;">Submit</button>

by that, the form is not re-submitted after showUser().

Upvotes: 0

Lavneet
Lavneet

Reputation: 626

code is correct except the button that you've created.

use: <input type="button" onclick="showUser(q.value)" value="Submit">

instead of: <button method="GET" onclick="showUser(q.value)">Submit</button>

What you've done is actually submitting the form. So, the onclick event is being overridden.

Upvotes: 2

Related Questions