DB Connection in html using php - php

I have a HTML page index2.html. In this page, I have a DIV which I am using to call a PHP page. The Php page has DB connection parameters, an SQL to fetch values from the DB.
However, when the PHP is called from the HTML, I am getting redirected to the PHP page. All I want is to use this stored procedure to get the data from the database.
HTML Code Snippet
</head>
<body>
<div id="background">
<div id="Layer0"><img src="images/Layer0.png"></div>
<div id="Layer2"><img src="images/Layer2.png"></div>
<div id="parceldeliveryservic"><img src="images/parceldeliveryservic.png"></div>
<div id="Layer10">
<form action="insert4.php" method="post">
<input type="image" src="images/Layer10.png"/>
</form>
</div>
The PHP Code Snippet:
<?php include("connect.php");
//$q = intval($_GET['q']);
try {
$proc_rate ='rtPreston';
$proc_price = 0.0;
$conn = new PDO("mysql:host=$servername;dbname=testdb", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//$sql = "GetPrice(?, ?)";
$sql = "Call GetPrice(:input, #output_price)";
$stmt = $conn->prepare($sql);
echo $proc_price;
$stmt->bindParam(':input',$proc_rate, PDO::PARAM_INT);
$stmt->execute();
$stmt->closeCursor();
$proc_price = $conn->query("SELECT #output_price AS output_price")->fetch(PDO::FETCH_ASSOC);
if ($proc_price) {
echo sprintf('Price for %s is %lf', $proc_rate, $proc_price['output_price']);
}
} catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
//$conn = null; ?>
can you please let me know what needs to be done to display the result in the calling HTML page?
Many thanks

HTML
<div onclick="callPHP();">Click me!</div>
Javascript
<script>
function callPHP() {
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) {
// xmlhttp.responseText contains the result of the PHP
alert( xmlhttp.responseText );
}
};
// Call the PHP
xmlhttp.open("GET", "insert4.php", true);
xmlhttp.send();
}
</script>

Related

How to show mysql data in html input box using ajax?

I am creating a simple order taking page. What I want is when I will start typing on the select customer input box , filtered based on my key stroke result will be shown below the input box.
As I am new in this field your advise / suggestion will be highly appreciated.
here is my javascript code :
function showCustomer(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
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 (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","searchcustomer.php?q="+str,true);
xmlhttp.send();
}
}
Here is my searchcustomr PHP code
$q=$_GET["q"];
define('HOSTNAME', 'localhost');
define('USERNAME', 'root');
define('PASSWORD', '');
define('DBNAME', 'order');
$conn = new mysqli(HOSTNAME, USERNAME, PASSWORD, DBNAME);
$sql = "SELECT cusname, cusarea, cusadd1,cusadd2,cusadd3,cuscity,cuspin,cusoldbal FROM tbl_customer where cusname like '%".$q."%'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()){
$data = $row['cusname'];
}
echo $data;
}
else
{
echo 'No Mach Found...';
}
$conn->close();
here is my HTML input file:
<h4>Order To</h4>
<div class="form-group">
<input type="text" class="form-control autocomplete_com" data-type="clientCompanyName" name="clientCompanyName" id="clientCompanyName" placeholder="Select Company" onkeyup="showCustomer(this.value)">
</div>
<div id="txtHint"></div>
This div txtHint just not working, I just want the result below my input box and able to select too.....What will be the best way to achieve that?

PHP, AJAX Unable to display values based on dropdownlist

My codes were taken from http://www.w3schools.com/php/php_ajax_database.asp, however i modified to better suit me, but it isn't working as it should be.
Afile.php
<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", "getDescription.php?q=" + str, true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<select name="users" onchange="showUser(this.value)">
<?php
$comCtrl = new company_controller();
$companyArray = $comCtrl->retrieveAllCompany();
foreach($companyArray as $com) {
echo "<option value ='".$com."' >".$com."</option>";
}//end foreach
?>
</select>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here.</b></div>
</body>
getDescription.php
<?php
require_once('dbManager.php');
$q = intval($_GET['q']);
$dbMgr = new dbManager();
$conn = $dbMgr->getDBConnection();
$query = "select company_address from company where company_name = '$q'";
$result = mysql_query($query);
echo "<table border='1'>";
while($row = mysql_fetch_assoc($result)) {
echo "<tr>";
echo "<td>" . $row['company_address'] . "</td>";
echo "</tr>";
}
echo "</table>";
$dbMgr->closeDBConnection($conn);
?>
dbManager.php
<?php
//require('/config/config.php');
require(dirname(__FILE__) . '\..\config\config.php');
class dbManager{
function getDBConnection(){
// start connection
$connect = mysql_connect(DB_HOST, DB_USER, DB_PASS);
if (!$connect)
{
die( 'Could not connect: '.mysql_error() );
}
// Select the database
if(!mysql_select_db(DB_NAME))
{
die('The database - '. DB_NAME .' does not exist!');
}
return $connect;
}
function closeDBConnection($connect){
// close the connection
mysql_close($connect);
}
}
?>
I was expecting to have the same result as shown on the website.
Instead, when i first run the files, i would see a dropdownlist(ddl) with all the company values, and beneath that ddl is the text "person info will be listed here". When i click on the ddl, i was hoping for the company's address to be populated at the div place of the text, but instead another ddl appeared beneath the first ddl. So now i have a ddl on the first row, another ddl on the second row, and the same text "person info will be listed here". WHat am i missing?
I would recommend you to use mysqli_query() or PDO::query()
This is the required syntax for mysql_query()
mysql_query(query,$conn);
use:
$q = trim($_GET['q']);

ajax get method

UPDATE... this is the code I've implemented from the tutorial, within chrome dev tools in network i can see in header the variable is being sent and in preview i can see the drop down menu however it is not inserted into the loaded webpage
<script type="text/javascript">
$(document).ready(function() {
$('#selectEvidence').change(function(){
alert($(this).val());
});
});
function evidencesearch(str)
{
if (str=="")
{
document.getElementById("case").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("case").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","searchfunction.php?variable="+str,true);
xmlhttp.send();
}
</script>
<?php
$variable = $_GET['variable']; //used for second drop down menu
//echo "test test test $variable";
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$db = 'fid';
$conn = mysql_connect($dbhost,$dbuser,$dbpass);
if (!$conn)
die('Could not connect: ' . mysql_error());
mysql_select_db($db);
echo '<label class="input" for="case" type="input">Specify: </label><select id="case" name="case"><option=value"null"></option>'; //Insert to loaded page
$resource = mysql_query("SELECT $variable FROM `evidence`");
if($resource && mysql_num_rows($resource)) {
while ($row = mysql_fetch_assoc($resource)){
echo '<option value="'.$row[$variable].'">'.$row[$variable].'</option></select>';//Insert to loaded page
}
}
mysql_close($conn)
?>
I think your problem sticks within POST/GET functions; try to call them synchronously and paste please the w3schools tutorial's link you mentioned. Maybe I can help you then by writing more detailed answer.
Cheers.

Insert mysql data using javascript and ajax

Basically I need to insert the value of a textarea asynchronously but when I call the function insertSQLData() it shows the source code of the page, besides that I cant find the other errors. I omitted the database code and any irrelevant code as well.
<?php
$q = $_GET["q"];
$username = $_COOKIE["user"];
?>
function insertSQLData(str){
if(str == 0){
document.getElementById("holder").innerHTML="";
return;
}
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("holder").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "index-async.php?q=+str", true);
xmlhttp.send();
}
<form action="" method="get">
<textarea onblur="insertSQLData(this.value);" id="quick-post-form" name="quick-post-form"></textarea>
<input type="button" value="Submit" name="quick-post-btn" id="quick-post-submit">
<div id="holder"></div>
if(isset($username) && !empty($q)){
mysql_query("INSERT INTO comments (comment,username) VALUES ('$q', '$username')");
} elseif(!empty($q)) {
mysql_query("INSERT INTO comments (comment,username) VALUES ('$q', 'Guest User')");
}
You have to load it before your php file starts up.
All you have to do is to write a controller, and use it anywhere instead of your index.php and in that, (after loading those things from DB) redirect user to your index.php page providing those data you need.
So you are calling same page where ajax call is..
obviously it returns the code.
write php code in another file and try to call it.
it works
You write code in conditional statement as per given below.
<?php
if(isset($_GET["q"]))
{
$q = $_GET["q"];
$username = $_COOKIE["user"];
if(isset($username) && !empty($q)){
mysql_query("INSERT INTO comments (comment,username) VALUES ('$q', '$username')");
} elseif(!empty($q)) {
mysql_query("INSERT INTO comments (comment,username) VALUES ('$q', 'Guest User')");
}
}
else
{
?>
<script>
function insertSQLData(str){
if(str == 0){
document.getElementById("holder").innerHTML="";
return;
}
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("holder").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "index-async.php?q=+str", true);
xmlhttp.send();
}
</script>
<form action="" method="get">
<textarea onblur="insertSQLData(this.value);" id="quick-post-form" name="quick-post-form"></textarea>
<input type="button" value="Submit" name="quick-post-btn" id="quick-post-submit">
<div id="holder"></div>
<?php
}
?>

Javascript PHP synchronisation problem

I want to call a javascript function with parametars that are stored in MySQL. All this is happening on an onClick event.
Here is the javascript code:
function getFile() {
if (window.XMLHttpRequest) {
AJAX=new XMLHttpRequest();
} else {
AJAX=new ActiveXObject("Microsoft.XMLHTTP");
}
if (AJAX) {
AJAX.open("POST", "gmap.php", false);
AJAX.send("searchField=" + searchField.value);
return load(AJAX.responseText);
} else {
return false;
}
}
So, the gmap.php is echoing the parameters for the javascript load function. But it doesn't load the parameter because the function is called before the MySQL query in gmap.php is executed. I've tried sync and async AJAX.
If I try to call the javascript function from PHP, it doesn't get executed, because it is called on a onClick event, and this is inside a div.
Please help me, I'm doing this over a week now. I've tried everything.
Here is the php code with the MySQL query:
<?php
header( 'Content-Type: text/html; charset=UTF-8' );
mb_internal_encoding( 'UTF-8' );
$a = $_POST['searchField'];
$dbhost = "localhost";
$dbuser = "*******";
$dbpass = "*******";
$dbname = "citydb";
//connect sql
mysql_connect($dbhost, $dbuser, $dbpass);
//select db
mysql_select_db($dbname) or die(mysql_error());
//retrieve data
//$city=$_GET['city'];
//escape user input to help prevent SQL injection
//$city=mysql_real_escape_string($city);
//query
mysql_query('SET CHARACTER SET utf8');
$result=mysql_query("SELECT citystart, cityend FROM cityids WHERE city='$a' ");
if(!result) {
die("Database query failed: " . myql_error());
}
while($row=mysql_fetch_array($result)) {
$lat=$row['citystart'];
$lng=$row['cityend'];
}
echo $lat;
echo ", ";
echo $lng;
?>
pass the php url together with the variable to search.
if (AJAX) {
var url = "gmap.php?searchField="+ searchField.value;
AJAX.open("POST", "url", false);
AJAX.send(true);
return load(AJAX.responseText);
}
I think searchField.value does not contain anything.
Replace
searchField.value
With this
document.getElementById('searchField').value
assign the searchField as an id to the search box.
add this code after AJAX.open and before AJAX.send.
AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
AJAX.setRequestHeader("Content-length", searchField.value.length);
AJAX.setRequestHeader("Connection", "close");
I have succesfully tested this
<html>
<head>
<script>
function load(response) {
alert(response);
}
function getFile() {
if (window.XMLHttpRequest) AJAX=new XMLHttpRequest();
else AJAX=new ActiveXObject("Microsoft.XMLHTTP");
if (AJAX) {
var params = "foo=" + searchField.value;
AJAX.open("POST", "http://localhost/test.php", true);
AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
AJAX.setRequestHeader("Content-length", params.length);
AJAX.setRequestHeader("Connection", "close");
AJAX.onreadystatechange = function() {
var ok;
try { ok=AJAX.readyState; } catch(e) { }
if(ok==4) load(AJAX.responseText);
}
AJAX.send(params);
}
}
</script>
</head>
<body>
<input type="text" id="searchField"/>
<input type="button" onclick="getFile()"/>
<script>
searchField = document.getElementById("searchField");
</script>
</body>
</html>

Categories