Why javascript is not working on a page which is called by ajax

countryajax.php

<?php
$con = mysqli_connect('localhost', 'root', '');
mysqli_select_db($con,"student");
?>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

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

Select Your Country
<select onChange="showUser(this.value)">
<?php
$sql="SELECT * FROM country";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
$id=$row['country_id'];
echo "<option value='$id'>" . $row['country_name'] . "</option>";
}
?>
</select>

<div id="txtHint" style="width:100px; border:0px solid gray;">
<b>your city disp here</b>
</div>

</body>
</html>

get-data.php

<html>
<head>
 <script>
		alert("script executed");
 </script>
</head>
<body>

<?php
//include('connectivity.php');
$con = mysqli_connect('localhost', 'root', '');
mysqli_select_db($con,"student");
$q=$_GET["q"];

$sql="SELECT * FROM state WHERE country_id ='$q'";

$result = mysqli_query($con,$sql);

 

echo "Your City <select>";
while($row = mysqli_fetch_array($result))
{
echo "<option>" . $row['state_name'] . "</option>";
}
echo "</select>";

//mysql_close($con);
?>

 

</body>
</html>

Script on get-data.php do not work.

Can you explain what you mean by “do not work”?

I mean when get-data.php is called.here the script tag do not work at all.

You mean that alert? You can’t execute JS within a PHP script like that; you’d need to echo that script block as well, so that it will be executed in the browser when the response is received and added to the DOM. (Although it would be appended to the select element then, which is not exactly valid HTML…)

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.