AJAX autopopulate using PHP - 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.

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?

Echo SQL query result to JS [duplicate]

I have a problem with my code.
case like this:
I have a dropdown, if selected "personal" it appeared the new dropdown that contains the data that is retrieved from a database query, if selected "public", then the dropdown disappear.
HTML code like this:
<select name="use" class="dropdown" id="sender" onChange='changeSend()'>
<option value=1>Public</option>
<option value=0>Personal</option>
</select>
<div id='send2'></div>
Query like this:
<?php
$query = mysql_query("select * from data where id_user = '$id_user' order by date asc");
$i = 0;
$id = array();
$name = array();
while($data = mysql_fetch_array($query)){
//id from result database query
$id[$i] = $data['id'];
//name from result database query
$name[$i] = $data['name'];
$i++;
}
?>
JavaScript code like this:
function changeSend() {
var selectBox = document.getElementById("sender");
var selectedValue = selectBox.options[selectBox.selectedIndex].value;
if (selectedValue==0) {
$('#send2').html("<select class='dropdown'><option value='-id from result database-'>-name from result database query-</option></select>");
} else {
$('#send2').html('');
}
}
I dont know how to send value/result ($id[0],$name[0],$id[1],$name[1], etc..) to javascript code(value and name in select options).
In javascript you have to make an ajax call to your php file:
var xmlhttp;
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("send2").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","yourFile.php",true);
xmlhttp.send();
And in your php file you have to echo your data in JSON format:
echo json_encode(array('id'=>$id,'name'=>$name));
UPDATE
in your case use the following code:
(not tested)
php code:
<?php
$query = mysql_query("select * from data where id_user = '$id_user' order by date asc");
$i = 0;
$options = array();
while($data = mysql_fetch_array($query)){
$options[$data['id']] = $data['name'];
}
echo json_encode($options);
?>
javascript code:
var xmlhttp;
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 response = JSON.parse(xmlhttp.responseText);
var select = '<select class='dropdown'>';
for( var index in response ){
select = select + "<option value='"+ index +"'>"+response[index]+"</option>";
}
select += "</select>";
document.getElementById("send2").innerHTML= select;
}
}
function changeSend() {
var selectBox = document.getElementById("sender");
var selectedValue = selectBox.options[selectBox.selectedIndex].value;
if (selectedValue==0) {
xmlhttp.open("GET","yourFile.php",true);
xmlhttp.send();
}
else {
$('#send2').html('');
}
}
USING jQuery
javascript code:
function changeSend() {
var selectBox = document.getElementById("sender");
var selectedValue = selectBox.options[selectBox.selectedIndex].value;
if (selectedValue==0) {
$.get("yourFile.php", function(data){
var response = JSON.parse(data);
var select = '<select class='dropdown'>';
for( var index in response ){
select = select + "<option value='"+ index +"'>"+response[index]+"</option>";
}
select += "</select>";
$("#send2").html(select);
});
}
else {
$('#send2').html('');
}
}
The best way would probably be with an ajax call, anyway if you are declaring the script in the same page with the php, you can json encode the array with the options so that you will be able to access it into the javascript, like this:
var optionIds = <php echo json_encode($id); ?>
var optionNames = <php echo json_encode($name); ?>

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

Checking If Email Exists In Database

I am checking if an e-mail exists in the database when a user is signing up for a new account. The "EmailMessage" is not coming up when I put in an e-mail that is in the database. Code located below:
validateemail.js
function validateemail() {
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 response = xmlhttp.responseText;
response = response.replace(/^\s+|\s+$/g,'')
if(response == 'error'){
document.getElementById("EmailMessage").innerHTML='This e-mail address is already taken! If you believe this is in error, please email support#pumpspy.com';
document.getElementById("newemail").focus();
document.getElementById("email_notice").style.display="none";
document.getElementById("submit_new_account").disabled =true;
}
else {
document.getElementById("EmailMessage").innerHTML="";
}
}
}
var newemail = document.getElementById("newemail").value;
if(newemail!=""){
xmlhttp.open("GET","Checkemail.php?email="+newemail,true);
xmlhttp.send();
}
else{
document.getElementById("EmailMessage").innerHTML="";
document.getElementById("submit_new_account").disabled =false;
}
}
Checkemail.php
$emailexists = $_GET['email'];
$sql = executeQuery("SELECT email from tbl_Users WHERE email = '$emailexists'");
$i = getNumRows($sql);
if ($i !=0) {
echo "error";
}else {
echo "pass";
}
---
<input type="text" id="newemail" name="newemail" maxlength="60" size="27" onblur="validateemail();"/>
</div>
<div id="EmailMessage" style="color:#F00"></div>
Try: $sql = executeQuery("SELECT email from tbl_Users WHERE email = '".$emailexists."'");
Also, please consider changing your code completely (concerns, security issues)...

JSON.parse(xmlhttp.responseText) unexpected character

I keep getting an unexpected character error in the console for the line
var a = JSON.parse(xmlhttp.responseText);
and I'm not sure why. Could this be why my textboxes aren't populating with the parsed data?
Main page code:
function loadDoc()
{
var xmlhttp;
// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
// code for IE6, IE5
else
{
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("textbox").innerHTML=a.first;
document.getElementById("textbox2").innerHTML=a.second;
}
}
xmlhttp.open("GET","loadTextBox.php?id=4",true);
xmlhttp.send();
}
loadTextBox.php code:
<?php
---Placeholder for correct DB login info---
$result = $mysql->query(---Placeholder for correct SQL query---);
while ($row = $result->fetch_object())
{
$queryResult[] = $row->present_tense;
}
$textboxValue = $queryResult[0];
$textboxValue2 = $queryResult[2];
echo json_encode(array('first'=>$textboxValue,'second'=>$textboxValue2));
?>
Your loadTextBox.php file should not contain any HTML because the JSON.parse method expects only JSON:
<?php
header("Content-type: application/json");
$db_username = placeholder;
$db_password = placeholder;
$db_host = placeholder;
$result = $mysql->query(---Placeholder for correct SQL query---);
while ($row = $result->fetch_object())
{
$queryResult[] = $row->present_tense;
}
$textboxValue = $queryResult[0];
$textboxValue2 = $queryResult[2];
echo json_encode(array('first'=>$textboxValue,'second'=>$textboxValue2));
?>
If your DB login info is in a separate file, then there should be no HTML or BODY tags only the PHP tags.

Categories