How to query SQLITE database from inside an HTML script - php

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>

Related

using ajax to load from a database

every type i run this it calls the error: OnError function and i can't see why it doesn't call the success: OnSuccess,
JS:
$(document).ready(function () {
// retreving data on button click
$("#data-submit").click(LoadDataThroughAjaxCall);
//loading screen functionality - this part is additional - start
$("#divTable").ajaxStart(OnAjaxStart);
$("#divTable").ajaxError(OnAjaxError);
$("#divTable").ajaxSuccess(OnAjaxSuccess);
$("#divTable").ajaxStop(OnAjaxStop);
$("#divTable").ajaxComplete(OnAjaxComplete);
//loading screen functionality - this part is additional - end
});
// ajax call
function LoadDataThroughAjaxCall() {
$.ajax({
type: "POST",
url: "Ajax/dataloader.php",
data: '{}',
dataType: "json",
success: OnSuccess,
failure: OnFailure,
error: OnError
});
// this avoids page refresh on button click
return false;
}
// on sucess get the xml
function OnSuccess(response) {
//debugger;
var xmlDoc = $.parseXML(response.d);
var xml = $(xmlDoc);
var tweets = xml.find("Table");
showOnATable(tweets);
}
// show data on a table
function showOnATable(tweets) {
//debugger;
var headers = [];
var rows = [];
// header section
headers.push("<tr>");
headers.push("<td><b>tweets</b></td>");
headers.push("<td><b>created</b></td>");
headers.push("<td><b>source</b></td>");
headers.push("</tr>");
// rows section
$.each(tweets, function () {
var tweets = $(this);
rows.push("<tr>");
rows.push("<td>" + $(this).find("tweet_text").text() + "</td>");
rows.push("<td>" + $(this).find("created_at").text() + "</td>");
rows.push("<td>" + $(this).find("source").text() + "</td>");
rows.push("</tr>");
});
var top = "<table class='gridtable'>";
var bottom = "</table>";
var table = top + headers.join("") + rows.join("") + bottom;
$("#divTable").empty();
$("#divTable").html(table);
}
// loading screen functionality functions - this part is additional - start
function OnAjaxStart() {
//debugger;
//alert('Starting...');
$("#divLoading").css("display", "block");
}
function OnFailure(response) {
//debugger;
alert('Failure!!!' + '<br/>' + response.reponseText);
}
function OnError(response) {
//debugger;
var errorText = response.responseText;
alert('Error!!!' + '\n\n' + errorText);
}
function OnAjaxError() {
//debugger;
alert('Error!!!');
}
function OnAjaxSuccess() {
//debugger;
//alert('Sucess!!!');
$("#divLoading").css("display", "none");
}
function OnAjaxStop() {
//debugger;
//alert('Stop!!!');
$("#divLoading").css("display", "none");
}
function OnAjaxComplete() {
//debugger;
//alert('Completed!!!');
$("#divLoading").css("display", "none");
}
PHP:
<?php
//if(isset($_POST['data'])==true&&empty($_POST['data'])==false){
require_once('../connection.php');
function clean($str)
{
if(get_magic_quotes_gpc())
{
$str= stripslashes($str);
}
return str_replace("'", "''", $str);
}
//Sanitize the POST values
//$username = clean($_POST['data']);
//$result=sqlsrv_query($conn,"execute sp_ORDER_BY_name '$username'");
$result=sqlsrv_query($conn,"select tweet_text,source from tweets");
if($result) {
if(sqlsrv_has_rows($result) > 0) {
//Login Successful
while( $row = sqlsrv_fetch_array( $result, SQLSRV_FETCH_ASSOC) ) {
echo $row['tweet_text'].", ".$row['source']."<br />";
}
}else {
//Login failed
echo 'Name not found';
}
}
//}
?>
HTML FORM:
</head>
<body>
<div id="banner">
<h1>P-CAT version 0.1</h1>
</div>
<div id ="content">
<h2>Sreach Catigroies</h2>
<select id="data2">
<option value="">Plece select one of the follwing</option>
<option value="Name">Name</option>
<option value="Location">Location</option>
</select>
<input name="data" id="data" type="text" />
<input type="submit" id="data-submit" value="Grab">
<div id="divTable">
</div>
</div>
<div id="divLoading" style="display: none; position: absolute; top: 50%; left: 40%;
text-align: left;">
<span>
<img src="Images/ajax-loader.gif" alt="Image not found." /></span>
<br />
<span style="text-align: left; padding-left: 8px;">Loading ...</span>
</div>
<div id="navbar">
<input type="button" value="EDIT">
<input type="button" value="HISTORY">
<input type="button" value="SETTINGS">
<input type="button" value="SEARCH">
</div>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="js/global.js"></script>
</body>
You have to response a json from php like,
if(sqlsrv_has_rows($result) > 0) {
//Login Successful
$xml='<Table>';
while( $row = sqlsrv_fetch_array( $result, SQLSRV_FETCH_ASSOC) ) {
$xml.='<tweet_text>'.$row['tweet_text'].'</tweet_text>';
$xml.='<source>'.$row['source'].'</source>';
// create xml tag for created_at
}
$xml.='</Table>';
echo json_encode(array('d'=>$xml));
return TRUE;
} else {
//Login failed
echo json_encode(array('d'=>'Name not found'));
}

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.

PHP and AJAX login form

Hello
I know this subject has been proposed before, but no one has done the AJAX manipulation standard like i did. I'm newbie to AJAX and jQuery
The problem I have here is that I'm not sure that the js function "ajaxPostCallManip()" reaches to "login.php"!!
I've made a couple of alert()s but nothing appears...Please help
HTML CODE
<link rel="stylesheet" type="text/css" href="jQuery-Files/jquery.mobile-1.3.1.css"/>
<script type="text/javascript" src="jQuery-Files/jquery-2.0.2.js"></script>
<script type="text/javascript" src="jQuery-Files/jquery.mobile-1.3.1.js"></script>
<script type="text/javascript" src="js/ajax.js"></script>
<div data-role="page" id="loginDialog">
<header data-role="header">
<h3 style="margin-left: auto; margin-right: auto;">Login or <a href="#regpage"
data-transition="flip">Register</a></h3>
</header>
<div data-role="content">
<form method="POST" action="" onsubmit="check_login(); return false;">
<fieldset data-role="contolgroup">
<div data-role="fieldcontain">
<label for="login_username">Username</label>
<input type="text" name="login_username" id="login_username"
placeholder="username" />
<label for="login_pwd">Password</label>
<input type="password" name="login_pwd" id="login_pwd"
placeholder="password" />
<div style="margin: auto; text-align: center;">
<label for="login_submit" class="ui-hidden-accessible">
Submit</label>
<button onclick="this.form.submit()" value="Submit"
data-inline="true"></button>
<span class="error" id="login_err" name="login_err"
style="display: none; font-size: 12px;
text-align: center;">status</span>
</div>
</div>
</fieldset>
</form>
</div>
</div>
js CODE
// AJAX Call handler using method="POST"
function ajaxPostCallManip( str, url, toDoFunc )
{
var xmlhttp; // Request variable
if( window.XMLHttpRequest ) // For modern browsers
xmlhttp = new XMLHttpRequest;
else // For old browsers
xmlhttp = new ActiveXOBject("Microsoft.XMLHttp");
xmlhttp.onreadystatechange=toDoFunc;
xmlhttp.open("POST", url, true);
xmlhttp.send(str);
}
function check_login()
{
// Construct the POST variables [username, password]
var postStr = "username=" + $('#login_username').val() + "&"
+ "password=" + $('#login_pwd').val();
// Call the general purpose AJAX Handler Function
ajaxPostCallManip(postStr, "login.php", function()
// toDoFunc to be performed when server response is ready
{
if( xmlhttp.readyState == 4 && xmlhttp.status == 200 )
{
alert(xmlhttp.responseText);
switch(xmlhttp.responseText)
{
case "1":
$('#login_err').css({'color':'green','display':'block'})
.html('Successful Login');
break;
case "2":
$('#login_err').css({'color':'red','display':'block'})
.html('incorrect username/password')
break;
case "3":
$('#login_err').css({'color':'red','display':'block'})
.html('please fill in all fields')
break;
}
}
});
}
PHP CODE
<?php
include('dbManip.php');
echo '<script> alert("Inside login.php"); </script>';
$username = $_POST['username'];
$password = $_POST['password'];
// Just to check that the POST variables arrived safely
echo "<script> alert('username = ' + $username); </script>";
if(!empty($username) && !empty($password))
{
// Fetch data from database
$query = "
SELECT username,password
FROM users
WHERE username = '$username' and password = '$password';
";
// Execute query
$res = mysql_query($query);
// If there is a match for the credentials entered with the database
if(mysql_num_rows($res) == 1)
{
// Fetch information and double check credentials
while($row = mysql_fetch_assoc($res))
{
$db_username = $row['username'];
$db_password = $row['password'];
}
// Compare results with user input
if( $username == $db_username && $password == $db_password)
{
// Credentials are correct - response = 1
echo '1';
}
else
{
// Credentials are incorrect - response = 2
echo '2';
}
}
else
{
// There is no match in the database
// Credentials are incorrect - response = 2
echo '2';
}
}
else
{
// If one or both fields are empty - response = 3
echo '3';
}
?>
First, you need to rewrite the submit button:
<button type="Submit" value="Submit"data-inline="true"></button>
Second, move the variable from a function that would make it a global:
var xmlhttp; // Request variable
function ajaxPostCallManip( str, url, toDoFunc )
{
if( window.XMLHttpRequest ) // For modern browsers
xmlhttp = new XMLHttpRequest;
else // For old browsers
xmlhttp = new ActiveXOBject("Microsoft.XMLHttp");
xmlhttp.onreadystatechange=toDoFunc;
xmlhttp.open("POST", url, true);
xmlhttp.send(str);
}
I think you need to rewrite this line of code:
<form method="POST" action="" onsubmit="check_login(); return false;">
And change it to:
<form method="POST" action="login.php" onsubmit="check_login(); return false;">
Make sure to save login.php in the same folder as your html file.
remove the method="post" and action="" attribute from the form tag because you are defining it in the ajax call
<button type="Submit" value="Submit"
var xmlhttp; // Request variable
function ajaxPostCallManip( str, url, toDoFunc )
{
if( window.XMLHttpRequest ) // For modern browsers
xmlhttp = new XMLHttpRequest;
else // For old browsers
xmlhttp = new ActiveXOBject("Microsoft.XMLHttp");
xmlhttp.onreadystatechange=toDoFunc;
xmlhttp.open("POST", url, true);
xmlhttp.send(str);
}

POST of multiple input form fields INTO mySQL db using AJAX

I'm trying to submit Multiple Form Items from HTML using Java-script into mySQL via AJAX request. I can get one field to update but not the other 2. I've commented out the other code I believed would aid in this but was not working.
HTML part:
<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”
“http://www.w3.org/TR/html4/loose.dtd”>
<head>
<script type="text/javascript">
function insert() {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('message').innerHTML = xmlhttp.responseText;
}
}
parameters = 'fname='+document.getElementById('fname').value;
xmlhttp.open("POST", "update.php", true);
xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xmlhttp.send(parameters);
} ;
</script>
</head>
<body>
First Name: <input class="work" type="text" id="fname" ><br>
Middle Name: <input class="work" id="mname" type="text"><br>
Last Name: <input class="work" id="lname" type="text"><br>
<input type="button" value="Submit" onclick="insert();">
<div id="message"></div>
</body>
</html>
PHP part:
<?php
//require 'connect.midasproject.php';
$conn_error = 'could not connect.';
$dbhost = "localhost";
$dbname = "mastergolddb";
$dbuser = "root";
$dbpass = "";
if (!#mysql_connect("$dbhost", "$dbuser", "$dbpass")||!#mysql_select_db ("$dbname")) {
die($conn_error);
} else {
echo 'connected.';
}
$fname = $_POST['fname'];
//$mname = $_POST['mname'] ;
//$lname = $_POST['lname'];
if (!empty($fname)) {
$query = "INSERT INTO `customers` VALUES ('','$fname','joe','blow')";
if ($query_run = mysql_query($query)) {
echo 'data inserted.' ;
} else {
echo 'Query failed.';
}
}
?>
you need to pass all 3 values to the ajax function. you seem to be passing just fname here
parameters = 'fname='+document.getElementById('fname').value;

For Search In PHP using Ajax

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>";

Categories