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

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?

Related

AJAX autopopulate using PHP

I am trying to populate two fields 'dep' and 'arr' when field 'flightnumber' is written into and 'onpointermove'.
Here is the form code:
<input type="text" name="flightnumber" id="flightnumber" onpointermove="showUser(this.value)" style="width: 70px;" maxlength="4">
<input type="text" name="dep" id="dep" style="width: 70px;">
<input type="text" name="arr" id="arr" style="width: 70px;">
Here is the AJAX
<script>
function showUser(str) {
if (str.length=="") {
document.getElementById("dep").innerHTML="";
document.getElementById("arr").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 (this.readyState==4 && this.status==200) {
var myObj = JSON.parse(this.responseText);
document.getElementById("arr").innerHTML = myObj.dep;
document.getElementById("dep").innerHTML= myObj.arr;
}
}
xmlhttp.open("GET","getdata.php?q=" + str,true);
xmlhttp.send();
</script>
And here is the php, which i have tested and does return correct results...
<?php
//look up the record based on email and get the firstname and lastname
$host_name = 'db5000091260.hosting-data.io';
$database = 'dbs85930';
$user_name = 'dbu68420';
$password = '';
$connect = mysqli_connect($host_name, $user_name, $password, $database);
$q = $_GET['q'];
$myObj->dep = "";
$myObj->arr = "";
$sql = "SELECT dep, arr FROM flights WHERE flightnumber = {$q}";
$result = mysqli_query($connect, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$myObj->dep = $row['dep'];;
$myObj->arr = $row['arr'];
$myJSON = json_encode($myObj);
echo $myJSON;
}
} else {
echo "0 results";
}
?>
I can only assume that the issue here is within the AJAX coding, as the PHP as mentioned is working.

Dropdown fetches data from database, wanting to make another dropdown that will multiply that number

Through some help from w3school, I managed to create a dropdown for out database, which would fetch the data about a certain product fine. That function is doing great, but I want to add an option for users to decide the number of products they want. To assist with that I want a dropdown that simply multiplies the prices gotten from the first database, if that is possible.
The PHP is the following
<?php
$con = mysqli_connect('localhost','root2','1234','LSnet');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$con->query('SET CHARACTER SET utf8');
if(isset($_GET['q']))
$q = intval($_GET['q']);
mysqli_select_db($con,'LSnet');
$sql = "SELECT * FROM Produkter Where id = '".$q."'";
$result = mysqli_query($con,$sql)
or die("Error: ".mysqli_error($con));
echo "<table>
<tr>
<th>Pris</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<td>" . $row['ProduktPris'] . ' DKK' . "</td>";
}
echo "</table>";
mysqli_close($con);
?>
and the HTML is the following
<script>
function showUser(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","../../prisdatabase.php?q="+str,true);
xmlhttp.send();
}
}
</script>
<body>
<form>
<select class="pris" name="NetTyper" onchange="showUser(this.value)">
<option value="">Vælg Nettype</option>
<option value="1">KampNet</option>
<option value="2">TræningNet</option>
</select>
</form>
<br>
<div id="txtHint"><b>Vælg Nettype her</b></div>
--
Added short overview of my table in the database.
--
The expected output from say option one would be 595 DKK, which I would like to have the option to multiply if one would need several

DB Connection in html using 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>

html code when updated by jquery has some issues

Well, I am developing a web page to view images in a grid image gallery. The images are categorized, and there's a left pane to select which category to view. Also, one of the links in the left pane is "My categories" which views all the categories as folder images in the grid.
I have a jquery script to change the images in the gallery when one of the categories is clicked, also when "My categories" is clicked it changes the images to images of folders for all the categories i have. Till now everything works fine.
The problem is that when I have "My categories" selected and the gallery is containing images of folders for all the categories I have, now I want to use the same jquery script so that when i click one of the "images of folders" which refer to one of the categories, the images in that category are viewed, but it's not working!
code for adding categories to left pane:
<ul class="nav nav-sidebar">
<li class="active"><b>Your Folders</b><span class="sr-only">(current)</span></li>
<?php
$db = mysql_connect("localhost", "root","");
$er = mysql_select_db("images", $db);
$sql="SELECT * FROM folder";
$result=mysql_query($sql);
while($row=mysql_fetch_array($result))
{
echo "<li><a class='folder' value='$row[folder_id]' title='$row[folder_name]' href='#'>&nbsp&nbsp&nbsp$row[folder_name]</a></li>";
}
?>
</ul>
html which adds images in gallery:
<div class="row" id="txtHint">
</div>
JQuery script to detect when "My categories" is selected:
$(".folders").click(function() {
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;
alert(xmlhttp.responseText);
}
}
xmlhttp.open("GET","getFolders.php?",true);
xmlhttp.send();
});
php code accessed by jquery:
<?php
$db = mysql_connect("localhost", "root","");
$er = mysql_select_db("images", $db);
$sql="SELECT * FROM folder";
$result=mysql_query($sql);
while($row=mysql_fetch_array($result))
{
echo "<div class='col-lg-3 col-sm-4 col-xs-6'><a title='$row[folder_name]' class='folder' value='$row[folder_id]' href='#'><img class='thumbnail img-responsive' src='folder.png'></a></div>";
}
?>
jquery which detects when one of the categories is selected:
$(document).ready(function() {
$(".folder").click(function() {
var $value = $(this).attr("value");
document.getElementById("title").innerHTML = $(this).attr("title");
if ($value == "") {
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 (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getImages.php?q="+$value,true);
xmlhttp.send();
}
});
php accessed by the jquery
<?php
$q = intval($_GET["q"]);
$db = mysql_connect("localhost", "root","");
$er = mysql_select_db("images", $db);
$sql="SELECT image_url, image_name FROM image WHERE folder_id=$q";
$result=mysql_query($sql);
while($row=mysql_fetch_array($result))
{
echo "<div class='col-lg-3 col-sm-4 col-xs-6'><a title='$row[image_name]' href='#'><img class='thumbnail img-responsive' src='$row[image_url]'";
}

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']);

Categories