Ajax Error : Not return database Value - javascript

I have a problem with my ajax php coding.
The problem is when the user enter their password to login ,the live checking function output only shown blank in select box below, not the data from database.
Below is my code:
Login.php
username:<input type="text" class="name" id="uname" placeholder="enter your username here"><br>
password:<input type="password" class="pass" id="pword" placeholder="password here"><br>
<div id="txt">
responsibility:<select id="opti">
<option value=""> Select your responsibility</option>
</select><br></div>
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txt").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("txt").innerHTML = this.responseText;
}
};
xmlhttp.open("POST","dblogin.php?q="+str,true);
xmlhttp.send();
}
}
document.getElementById('pword').addEventListener("keyup", function(str) {
showUser(str);
}, false);
</script>
Dblogin.php
<?
$q=intval($_POST["pword"]);
require ("config.php");
$link=mysqli_connect($host,$user,$pass,$db);
$query="select responsibility from testing where password = '".$q."'";
$result=mysqli_query($link,$query);
if($result){
?>
<form>
responsibility:<select id="opti">
<?
while($row=mysqli_fetch_array($result))
echo"<option value='$row[1]'>$row[1]</option>";
?>
</select>
<input type=submit value ="submit">
<?
}
else
{
?>
Error:No Data Found
<?
}
?>
config.php
<?
$host="localhost";
$db="logindb"
$user="root"
$pass="";
?>
the ajax function is work, but the database data not shown. Can anybody tell me what wrong with my coding.

Related

Ajax/PHP - autocomplete value not recognised

I am using this example to run an ajax data query from an mysql db, that returns a table.
This is working fine when text is manually typed into this input form eg:
But the search form has an autocomplete jquery script that will help the user along. When a value is chosen from the dropdown autocomplete values, the onchange event isn't recognized, no table shows.
My question is, how would I put a button at the end of the search form, to change this to 'onclick' event, rather than 'onchange'? The hurdle I am facing is that the input for 'client_address' is part of a larger form, and clicking submit on any button causes the page to try submit the entire form.
create_wt.php:
// autocomplete
<script type="text/javascript">
$(function() {
$( "#clientsearch" ).autocomplete({
source: 'backend_search_addressWT.php'
});
});
</script>
// retrieve data in table
<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","ajax_get_client_info.php?q="+str,true);
xmlhttp.send();
}
}
</script>
<div class="form-group <?php echo (!empty($client_address_err)) ? 'has-error' : ''; ?>">
<label>Address</label>
<div class = "input-group">
<input id="clientsearch" type="text" name="client_address" onchange="showUser(this.value)" class="input-group form-control" value="<?php echo $client_address; ?>" placeholder="Search by address..." style="width: 500px;">
<!---<span class="input-group-btn">
<button class="btn btn-success" value="submit" id="ajaxbtn" type="submit">Get Client Info</button>
</span> -->
</div>
<br><div id="txtHint"><b>Person info will be listed here...</b></div>
<span class="help-block"><?php echo $client_address_err;?></span>
</div>
ajax_get_client_info.php:
<?php
require_once 'config.php';
$q = trim($_GET['q']);
$query = $mysqli->query("SELECT * FROM client WHERE client_address LIKE '%".$q."%'");
//$data = array();
//while ($row = $query->fetch_assoc()) {
// $data[] = ($row);
//}
//echo json_encode($data);
echo "<table>
<tr>
<th>client_id</th>
<th>Client Name</th>
<th>Phone Number</th>
</tr>";
while($row = mysqli_fetch_array($query)) {
echo "<tr>";
echo "<td>" . $row['client_id'] . "</td>";
echo "<td>" . $row['client_name'] . "</td>";
echo "<td>" . $row['client_phone'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
EDIT:
create_wt:
<script type="text/javascript">
$(function() {
$( "#clientsearch" ).autocomplete({
select: 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","ajax_get_client_info.php?q="+str,true);
xmlhttp.send();
}
}
}
{
source: 'backend_search_addressWT.php'
});
});
</script>
According to jQuery UI Autocomplete documentation:
http://api.jqueryui.com/autocomplete/#event-select
the select event of the autocomplete input does not accept the user's input as an argument but has 2 other: event, ui.
So you are trying to access the value: ui.item.value that is the selected item's value.
So that must be your problem.
CBroe has the same answer in the comments.
....
function getHint(value) {
if ((value !== "") && (typeof value !== 'undefined')) {
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","ajax_get_client_info.php?q=" + value, true);
xmlhttp.send();
return true; // return true to accept the selection of the user
} else {
document.getElementById("txtHint").innerHTML = "";
$(this).autocomplete( "close" ); // Close the autocomplete popup manual because by returning false negates the selection but it does not close the popup.
return false; // return false to negate the selection of the user
}
}
$( "#clientsearch" ).autocomplete({
select: function showUser(event, ui) {
return getHint(ui.item.value);
},
change: function showUser(event, ui) {
return getHint(ui.item.value);
},
{
source: 'http://www.example.com'
}
});
....
Be sure to read the documentation so you know how to treat this case from the start.
Hope this helps.
Change onchange in input box to onkeyup, that should solve, onchange is mainly used for radio buttons and checkboxes.
<input id="clientsearch" type="text" name="client_address" onkeyup="showUser(this.value)" class="input-group form-control" value="<?php echo $client_address; ?>" placeholder="Search by address..." style="width: 500px;">
Use a input type button:
<input type="button" name="" id="">
and use its click event. Input type will not submit the form.

Fetching column value from DB for a Select Option

I've a drop-down list for selecting an Id on a php page, the values of which is getting fetched from the database(1st Column).
There's a text-field next to the drop-down in which I want to display the name of the member (2nd Column) from the database.
The code is below -
<?php
include ('connection.php');
$query = "SELECT Member_id FROM member_db ORDER BY Member_id ASC";
$result = mysqli_query($conn, $query) or die(mysqli_error($conn)."[".$query."]");
?>
<Select id="st_id" placeholder="Enter Member id" name="ist_id" required class="styled-select green semi-square onChange="showMember(this.value)"">
<option selected ="true" disabled="disabled">Select Member Id</option>
<?php while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)){?>
<option value=" <?php $row['Member_id']; ?> ">
<?php echo $row['Member_id'];?>
</option>
<?php }?>
</Select>
<input style="min-height:30px" type="text" id="st_name" placeholder="Member name" name="ist_name" disabled/>
The JavaScript code I'm calling is this -
function showMember(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","getMember.php?q="+str,true);
xmlhttp.send();
}
}
The getMember.php is another php file in which I'm firing a query to get the Member_name based on the value of Member_id.
But the problem is that somehow, that onChange, the page doesn't call the showMember() function.
1) Missing echo in value attribute <option value="<?php $row['Member_id']; ?> "> <?php echo $row['Member_id'];?>
2) onchange should be outside the class attribute .<Select id="st_id" placeholder="Enter Member id" name="ist_id" required class="styled-select green semi-square" onChange="showMember(this.value)">
simple use jquery ajax
function showMember(str)
{
$.ajax({
url:'getMember.php',
type:'post',
data:{q:str},
success:function(data)
{
$('#st_name').val(data);
}
});
}
Note :don't forgot to include jquery

div don't show up. Why?

I create a javascript + a php page. The script on the php page send data to my sql database, but don't show the result into on my home page.
Here the code
function getVote(question_ID) {
var option_ID = document.querySelector("input[id='option']:checked").value;
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 (option_ID.readyState == 4 && option_ID.status == 200) {
document.getElementById(poll).innerHTML = option_ID.responseText;
}
}
xmlhttp.open("GET", "./core/vote.php?user_ID=" + user_ID + "&question_ID=" + question_ID + "&option_ID=" + option_ID, true);
xmlhttp.send();
}
<div id="poll">
</div>
More code
<div id="poll">
<form method="post" onsubmit='getVote(question_ID);' >
<p><?php echo $question ['question_content']; ?></p>
<p>
<?php
$poll_option_selection = "SELECT option_ID, option_content FROM poll_options WHERE question_ID='$question_ID'" ;
$poll_option_result = mysqli_query ($connect,$poll_option_selection) ;
foreach ($poll_option_result as $poll_option) {
$option_ID = $poll_option ['option_ID'] ;
$option_content = $poll_option ['option_content'] ;
?>
<script type="text/javascript">
var option_ID = <?php echo json_encode($option_ID) ; ?> ;
</script>
<input type="radio" id="option" value ='<?php echo $option_ID ?>' required />
<?php echo $option_content ?>
</br>
<?php
}
?>
<input type="submit">
</form>
</div>
Thank you for your help
It should be:
document.getElementById("poll").innerHTML=option_ID.responseText;
document.getElementById takes the argument (id of element) as a string.

checking Email availablity using AJAX in php

i need to check email availablity for this task. while i enter any email address, after i press tab it should check in the database and return whether this email are already exist or not.
but this routine gives exact output as what i expect while checking it in console. but the error message didn't written on my html page. can any one help me? thanks in advance.
HTML coding
<div class="txtinputcomp">
<input name="frmVisitorEmail" id="frmVisitorEmail" onblur="checkEmail(this.value);" class="emailbox" required="required" value="<?php echo $_POST['frmVisitorEmail']; ?>" placeholder="Visitor Email" type="email" />
</div>
<div class="emptytxtcomp">
<span id="errorEmail" class="errorStyle"></span>
</div>
FindEmail.php
<?php
include("includes/config.php");
$strEmail = $_GET["email"];
$strData = doCheckEmail($strEmail);
if($strData!=0) {
echo "<script type='text/javascript'>
document.getElementById('errorEmail').innerHTML = 'Email address are already exist!';
return false;
</script>";
} else {
echo '<script type="text/javascript">
document.getElementById("errorEmail").innerHTML = "";
</script>';
}
?>
AJAX script
function checkEmail(str)
{
var xmlhttp;
if (str.length==0) {
document.getElementById("frmVisitorEmail").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("frmVisitorEmail").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","findEmail.php?email="+str,true);
xmlhttp.send(null);
}
Function
function doCheckEmail($strIdent)
{
$strSelectsSql = "Select count(*) as TotalCnt from tbl_visitor Where visitor_email='".$strIdent."' ";
$strSelectsResult = SelectQry($strSelectsSql);
return $strSelectsResult[0][0];
}
function SelectQry($Qry) {
$result = mysql_query($Qry) or die ("QUERY Error:".$Qry."<br>".mysql_error());
$numrows = mysql_num_rows($result);
if ($numrows == 0) {
return;
} else {
$row = array();
$record = array();
while ($row = mysql_fetch_array($result)) {
$record[] = $row;
}
}
return MakeStripSlashes($record);
}
This line won't run the script that the PHP is echoing:
document.getElementById("frmVisitorEmail").innerHTML=xmlhttp.responseText;
In order to execute dynamically-added Javascript, you have to use createElement to create a script element.
Instead, I suggest that the PHP just return the error message, not a script block. So it should be:
if($strData!=0) {
echo "Email address are already exist!";
} else {
echo "";
}
Then the Javascript would be:
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status==200) {
document.getElementById("errorEmail").innerHTML=xmlhttp.responseText;
}
}

Ajax Mysql Query

I am propably being a complete idiot and not seeing the big picture here. I am trying to write a little ajax thingie that would pull information from a database but i cant seem to get the thing going ... please tell me what i am doing wrong.
I put the code together by following a couple of online tutorials and i am no ajax genius. my ajax skills could propably start the next world war.
Here is my code. please feel free to tell me im an idiot if i missed something small.
<html>
<head>
<script>
function showDetail(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","process.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
Wallet Number : <input type="text" name="wallet01" id="wallet01" />
<br />
<input type="submit" id="submit" name="submit" onsubmit="showDetail(wallet01)">
</form>
<br>
<div id="txtHint"><b>Kit info will be listed here.</b></div>
</body>
</html>
and here is my php
<?php
$q = $_GET['q'];
$con = mysqli_connect('10.1.75.131','markdv','qwerty123','MTNAutomation');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"MTNAutomation");
$sql="SELECT serialNumber FROM Kit_T WHERE serialNumber = '$q'";
$result = mysqli_query($con,$sql);
echo "<table border='1'>
<tr>
<th>Wallet Number</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['serialNumber'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
There is an error in your HTML. You put 'onsubmit="showDetail(wallet01)"', but 'wallet01' is not a javascript variable.
I would suggest changing it to this:
<form onsubmit="return showDetail()">
Wallet Number : <input type="text" name="wallet01" id="wallet01" />
<br />
<input type="submit" id="submit" name="submit">
</form>
I added the "onsubmit" in the form, using the function with "return", to prevent the default submit from form. But remember to always return false in the function.
Than in the function you can get the value for the field.
function showDetail() {
var str = document.getElementById('wallet01').value;
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return false;
}
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","process.php?q="+str,true);
xmlhttp.send();
return false;
}
Or you can use the ajax from jQuery, it's easier.
See an example here
function showDetail() {
var str = $('#wallet01').val();
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return false;
}
var jqxhr = $.ajax( {
url: "example.php",
type: "GET",
data: {q: str}
}).done(function(data, textStatus, jqXHR ) {
alert( "success" );
}).fail(function(jqXHR, textStatus, errorThrown) {
alert( "error" );
}).always(function( ) {
alert( "complete" );
});
return false;
}
See the JQuery Ajax docs
You also have the function "beforeSend" to start a gif "loading".

Categories

Resources