For Search In PHP using Ajax - php

I perform live search in php using ajax. This is my code for performing task
googleajax.php
<?php
$id=$_GET['id'];
if(isset($_POST['submit']))
{
$temp=$_POST['name'];echo $temp;
}
?>
<html>
<head>
<script language="javascript" type="text/javascript">
function getXMLHTTP() { //function to return the xml http object
var xmlhttp=false;
try{
xmlhttp=new XMLHttpRequest();
}
catch(e) {
try{
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e){
xmlhttp=false;
}
}
}
return xmlhttp;
}
function getValue(id)
{
var strURL="googledata.php?id="+id;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('div1').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
</script>
</head>
<body>
<form method="post">
<?php
/*$query="Select * from tblcountry where country_id='".$id."'";
echo $
$res=mysql_query($res);
while($row=mysql_fetch_assoc($res))
{
extract($row);*/
?>
<input type="text" id="name" name="name" onKeyUp="getValue(this.value)" value="<?php echo $id;?>" />
<input type="submit" id="submit" name="submit" value="serch">
<div id="div1" name="div1">
</div>
<?php
/*<!--}-->*/
?>
</form>
</body>
</html>
and googledata.php
<?php
$con=mysql_connect("localhost","root","");
if(!$con)
{
die("error in connection");
}
else
{
mysql_select_db("hms2012",$con);
}
$id= $_GET['id'];
if($id=="")
{
}
else
{
$result=mysql_query("select * from tblcountry where country_name like '$id%'");
while($row=mysql_fetch_assoc($result))
{
extract($row);
echo "<option value='$country_id'><a href='googleajax.php?id=$country_id'>".$country_name."</a><br></option>";
}
}
?>
Performing this code I can not select value for press key.
What was the use that I can select the value?

You have no <select></select> around your <options> tags list.
You should take a look on using jQuery for your Ajax stuff.

what is $country_id and $country_name. I have changed it by assumption. Please check.
echo '<select name="somename">';
while($row=mysql_fetch_assoc($result))
{
extract($row);
echo "<option value='".$row['country_id']."'><a href='googleajax.php?id=".$row['country_id']."'>".$row['country_name']."</a><br></option>";
}
echo "</select>";

Related

How to query SQLITE database from inside an HTML script

What's the write syntax to query an SQLITE database from inside an HTML script?
The code below (which btw works perfectly when used in a separate php file) doesn't return anything in the textarea....
Any help would be highly appreciated. Thanks
<p>Patient search:</p>
<textarea id="SearchBoxPt" textarea name="SearchBoxPt" style="height: 30px; resize: none; width: 600px;">
</textarea></p>
<button type="button" onclick="populateField_SearchPt()">Load Pt 1</button>
<script>
function populateField_SearchPt()
{
<?php
class MyDB extends SQLite3
{
function __construct()
{
$this->open('Anagrafica.db');
}
}
$db = new MyDB();
if(!$db)
{
echo $db->lastErrorMsg();
} else
{
echo "Opened database successfully\n\n";
}
$results = $db->query('SELECT name FROM Anagrafica WHERE hospital_ID="1"');
?>
document.getElementById ("SearchBoxPt").value = $results;
}
</script>
Here is an example
PHP
<?php
class MyDB extends SQLite3
{
function __construct()
{
$this->open('Anagrafica.db');
}
}
$db = new MyDB();
if(!$db)
{
echo $db->lastErrorMsg();
}
$hId = $_GET['hId']; //we're getting the passed hId as a paramater in the url
$query = $db->prepare("SELECT name FROM Anagrafica WHERE hospital_ID=:id");
$query->bindValue(':id', $hId, SQLITE3_INTEGER);
$results = $query->execute()->fetchArray();
echo $results['name'];
?>
HTML
<p>Enter Hospital Id:
<input id="HospitalId" type="number" value="1">
</p>
<p>Patient search:</p>
<textarea id="SearchBoxPt" textarea name="SearchBoxPt" style="height: 30px; resize: none; width: 600px;">
</textarea>
</p>
<button type="button" onclick="populateField_SearchPt()">Load Pt 1</button>
<script>
function populateField_SearchPt()
{
var inputId = document.getElementById("HospitalId").value; //we get the user input value and put it in a var
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "path/to/yourPhpFile.php?hId=" + inputId, true); // we're passing the hId to the server as a parameter
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("SearchBoxPt").value = this.responseText;
}
};
xhttp.send();
}
</script>
You can not put php scripts in javascript knowing that php is executed in the server side and not on the browser.
The solution is to keep your php code into a seperated file and make an ajax call to your php on every button click to retreive data from database.
PHP
<?php
class MyDB extends SQLite3
{
function __construct()
{
$this->open('Anagrafica.db');
}
}
$db = new MyDB();
if(!$db)
{
echo $db->lastErrorMsg();
}
$results = $db->query('SELECT name FROM Anagrafica WHERE hospital_ID="1"')->fetchArray();
echo $results['name'];
?>
HTML
<p>Patient search:</p>
<textarea id="SearchBoxPt" textarea name="SearchBoxPt" style="height: 30px; resize: none; width: 600px;">
</textarea>
</p>
<button type="button" onclick="populateField_SearchPt()">Load Pt 1</button>
<script>
function populateField_SearchPt()
{
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "path/to/yourPhpFile.php", true);
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("SearchBoxPt").value = this.responseText;
}
};
xhttp.send();
}
</script>

PHP setting JSON values to Textboxes

This is the html file.
<html>
<head>
<script>
function showUser(str) {
if (str == "") {
return;
} else {
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)
{
var doc = window.document.createElement("doc");
var a = JSON.parse(xmlhttp.responseText);
document.getElementById("stuname").value=a.first;
document.getElementById("branch").value=a.second;
document.getElementById("year").value=a.third;
document.getElementById("category").value=a.four;
}
}
xmlhttp.open("GET","test2.php?q="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<form>
Roll Number:<br>
<input type="text" name="rollno" id="rollno" onblur="showUser(this.value)">
<br>
Student Name:<br>
<input type="text" name="stuname" id="stuname" value="">
Branch:<br>
<input type="text" name="branch" id="branch" value="">
Year:<br>
<input type="text" name="year" id="year" value="">
Category:<br>
<input type="text" name="category" id="category" value="">
</form>
<br>
</body>
</html>
test2.php file
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
$q = $_GET['q'];
$con=mysqli_connect("localhost","root","neel","sitams");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT rollno,stuname,branch,category FROM studet where rollno='".$q."' and academic='2014-2015'";
if ($result=mysqli_query($con,$sql))
{
while ($obj=mysqli_fetch_object($result))
{
$queryResult[] = $obj->rollno;
$queryResult[] = $obj->stuname;
$queryResult[] = $obj->branch;
$queryResult[] = $obj->category;
}
}
$textboxValue1 = $queryResult[0];
$textboxValue2 = $queryResult[1];
$textboxValue3 = $queryResult[2];
$textboxValue4 = $queryResult[3];
echo json_encode(array('first'=>$textboxValue1,'second'=>$textboxValue2,'third'=>$textboxValue3,'four'=>$textboxValue4));
?>
</body>
</html>
I could not able to load values to the text boxes where is fault. Even I have seen stackoverflow but I could not able to get it. when I type test2.php by passing rollno value to q it will display data but when I pass a value from html it could not able to set the values to the textbox fields.
Remove any html tags from test2.php . An ajax document does not need any html tags.
Hi this one will be helpful to you .
<html>
<head>
</head>
<body>
<input type="button" onclick="showUser('ok');" value="click to ru me" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function showUser(str)
{
if (str=="")
{
return;
}
else
{
if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); }
else { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
//var doc = window.document.createElement("doc");
var parsed = JSON.parse(xmlhttp.responseText);
for(var x in parsed)
{
var First=parsed[x].first;
var Second=parsed[x].second;
var Third=parsed[x].third;
var Fourth=parsed[x].fourth;
console.log("first="+First+" second="+Second+" third="+Third+" fourth="+Fourth);
document.getElementById("stuname").value=parsed[x].first;
document.getElementById("branch").value=parsed[x].second;
document.getElementById("year").value=parsed[x].third;
document.getElementById("category").value=parsed[x].fourth;
}
}
}
xmlhttp.open("GET","phpex.php?q="+str,true);
xmlhttp.send();
}
}
</script>
<input type="text" id="stuname" />
<input type="text" id="branch" />
<input type="text" id="year" />
<input type="text" id="category" />
</body>
</html>
Ajax File Name phpex.php . ajax page code is below
<?php
echo '[{"first":"1111","second":"2222","third":"3333","fourth":"4444"}]';
?>

Xmlhttp error in ajax

I have country and states select box which loads based on the selection of country. This code is working fine offline but when i put it to server it says (Problem while using XMPHTTP: Not Found).
<script language="javascript" type="text/javascript">
function getXMLHTTP() { //function to return the xml http object
var xmlhttp=false;
try{
xmlhttp=new XMLHttpRequest();
}
catch(e) {
try{
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1){
xmlhttp=false;
}
}
}
return xmlhttp;
}
function getState(cate_id) {
var strURL="findsect.php?country="+cate_id;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('statediv').innerHTML=req.responseText;
} else {
alert("Problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
</script>
This code is in findsect.php
<html>
<head>
<title></title>
<style type="text/css">
.input-short {
width: 25%
}
</style>
</head>
<?php
$country=$_GET['country'];
$con = mysql_connect('localhost','root','');
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('my');
$query="SELECT * FROM gallery_section WHERE related='$country'";
$result=mysql_query($query);
?>
<select class="input-short" name="Section" onchange="getCity(<?php echo $country?>,this.value)">
<option>Select Section</option>
<?php while ($row=mysql_fetch_array($result)) { ?>
<option value="<?php echo $row['title']?>"><?php echo $row['title']?></option>
<?php } ?>
</select>
</html>

Ajax search not Working whereas the XML already running?

I'm a newbie on Ajax, I have tried the tutorial Book, but it did not work. The code is for searching.
This is the script search.htm
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>AJAX + MySQL I</title>
<script type="text/javascript" src="search.js"></script>
</head>
<body onload='process()'>
<h1>Student Search</h1>
<form name="form1">
Masukkan Nama Mahasiswa: <input type="text" id="namaMhs" />
</form>
<p><strong>Hasil Pencarian :</strong></p>
<div id="hasil" />
</body>
</html>
and the JS script search.js
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject()
{
var xmlHttp;
if(window.ActiveXObject)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
xmlHttp = false;
}
}
else
{
try
{
xmlHttp = new XMLHttpRequest();
}
catch (e)
{
xmlHttp = false;
}
}
if (!xmlHttp) alert("Obyek XMLHttpRequest tidak dapat dibuat");
else
return xmlHttp;
}
function process()
{
if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
{
nama =
encodeURIComponent(document.getElementById("namaMhs").value);
xmlHttp.open("GET", "search.php?namaMhs=" + nama, true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}
else
setTimeout('process()', 1000);
}
function handleServerResponse()
{
if (xmlHttp.readyState == 4)
{
if (xmlHttp.status == 200)
{
var xmlResponse = xmlHttp.responseXML;
xmlRoot = xmlResponse.documentElement;
nimArray = xmlRoot.getElementsByTagName("nim");
namaMhsArray = xmlRoot.getElementsByTagName("namamhs");
alamatArray = xmlRoot.getElementsByTagName("alamat");
if (nimArray.length == 0)
{
html = "Data tidak ditemukan";
}
else
{
// membentuk tabel untuk menampilkan hasil pencarian
html = "<table border='1'><tr><th>NIM</th><th>Nama
Mhs</th><th>Alamat</th></tr>";
for (var i=0; i<nimArray.length; i++)
{
html += "<tr><td>" + nimArray.item(i).firstChild.data +
"</td><td>" +
namaMhsArray.item(i).firstChild.data +
"</td><td>" +
alamatArray.item(i).firstChild.data +
"</td></tr>";
}
html = html + "</table>";
}
document.getElementById("hasil").innerHTML = html;
setTimeout('process()', 1000);
}
else
{
alert("Ada masalah dalam mengakses server: " +
xmlHttp.statusText);
}
}
}
and the last script in php search.php
<?php
header('Content-Type: text/xml');
echo '<hasil>';
$namaMhs = $_GET['namaMhs'];
mysql_connect("localhost","root","*******");
mysql_select_db("mahasiswa");
$query = "SELECT * FROM mhs WHERE namamhs LIKE '%$namaMhs%'";
$hasil = mysql_query($query);
while ($data = mysql_fetch_array($hasil))
{
echo "<mhs>";
echo "<nim>".$data['NIM']."</nim>";
echo "<namamhs>".$data['NAMAMHS']."</namamhs>";
echo "<alamat>".$data['ALAMAT']."</alamat>";
echo "</mhs>";
}
echo '</hasil>';
?>
Please help me to fix this script. The XML on search.php is already running but my searching is not. Any help is appreciated.
You are submitting the script on load, before there is even a value in the text field:
<body onload='process()'>
<h1>Student Search</h1>
<form name="form1">
Masukkan Nama Mahasiswa: <input type="text" id="namaMhs" />
</form>
You should either add a value to the text field as such:
<input type="text" value="testname" id="namaMhs" />
Or as a better option, add a submit button and don't run the function on load, but rather on submit:
<body>
<h1>Student Search</h1>
<form name="form1">
Masukkan Nama Mahasiswa: <input type="text" id="namaMhs" />
<input type="button" value="Search" onclick="process();" />
</form>
There may be more or even many more problems with your code, I am not looking through it all, but this should get you off to a good start.

Ajax check if username exists

I am having trouble to get my code working. As a user types in a username it checks the database to see if it exists and if it does sets the <P id="checkusername"> to "Username Taken." and if not sets it to "Not Taken." I can't see why my code is not working.
1-register.html
<html>
<body>
<CENTER>
<form name="register" action="register.php" method="post">
Username: <input type="text" name="username" onkeyup="checkUsername(this.value)" />
<P id="checkusername">checker</P>
<input type="submit" value="Login" />
</form>
</CENTER>
<script type="text/javascript">
function checkUsername(){
var xmlhttp;
var username=document.forms["register"]["username"].value;
if(username.length==0){
document.getElementById("checkusername").innerHTML="Empty";
return;
}
if(window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
var url = "login.php";
var params = "header=checkusername&username="+username+"&password="";
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.onreadystatechange = function() {//Call a function when the state changes.
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("checkusername").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.send(params);
}
</script>
</body>
</html>
2-register.php
<?php
$header = $_POST["header"];
if(header=="checkusername"){
checkusername($_POST["username"]);
}else{
echo "No match: " . $header;
}
function connection(){
$con = mysql_connect(URL, username, password);
if(!$con){
die('Could not connect: ' . mysql_error());
}
return $con;
}
function checkusername($username){
$con = connection();
mysql_select_db(database, $con);
$result = mysql_query("SELECT * FROM users WHERE username = \"" . $username . "\";");
while($row = mysql_fetch_array($result)){
if(($row['username'] == $username)){
echo "Username Taken.<br/>";
return;
}
}
echo "Not Taken.";
}
mysql_close();
?>
Read this Blog http://papermashup.com/jquery-php-mysql-username-availability-checker/

Categories