How to autofill textbox from suggestion list? - javascript

I am a beginner in jquery and ajax. I'm trying to get google like suggestion while typing in the textbox. However I've tried for hours and still can't get to view the suggestion as a list and autofill the textbox while selecting text from the list. Here is what I've tried so far.
The php file-
$conn = new mysqli("host", "user", "pass", "database");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT data1, data2 FROM table";
$result = $conn->query($sql);
// get the q parameter from URL
$q = $_REQUEST["q"];
$hint = "";
while ($row = $result->fetch_assoc()){
// lookup all hints from array if $q is different from ""
if ($q !== "") {
$q = strtolower($q);
$len=strlen($q);
foreach($row as $name) {
if (stristr($q, substr($name, 0, $len))) {
if ($hint === "") {
$hint = $name;
}
else {
$hint .= "</br> <a href='#'>$name </a>";
}
}
}
}
}
// Output "no suggestion" if no hint was found or output correct values
echo $hint === "" ? "no suggestion" : $hint;
The Javascript code-
function showHint(str) {
if (str.length == 0) {
document.getElementById("livesearch").innerHTML = "";
document.getElementById("livesearch").style.border="0px";
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) {
document.getElementById("livesearch").innerHTML=this.responseText;
document.getElementById("livesearch").style.border="1px solid #A5ACB2";
}
}
xmlhttp.open("GET","getdb.php?q="+str,true);
xmlhttp.send();
}
The html file-
<p><b>Start typing a name in the input field below:</b></p>
<div>
<form>
First name: <input type="text" onkeyup="showHint(this.value)">
<div id="livesearch">
</div>
</div>
Another problem is the first suggestion from the list isn't appearing as a link like rest of the suggestion.
Screenshot
How can I list my suggestions properly and how can I can fill the textbox when a user selects text from the list. Pl's help!

Solved it myself few days ago. Here is what the code looks like so far.
The php file-
$q = $_REQUEST["q"];
//$hint = "";
$sql = "SELECT data FROM tables WHERE Firstdata LIKE '%" . $q . "%' OR Lastdata LIKE '%" . $q ."%'";
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()){
$FirstData =$row['Firstdata'];
$LastData =$row['Lastdata'];
$ID=$row['ID'];
//-display the result of the array
if ($q !== "") {
echo "<li class="."list-group-item".">"
. "<a href=\"phpfile.php?id=$ID\">" .
$FirstData ." ". $LastData . "</a>
</li>";
}
}
The Javascript code-
function showHint(str) {
if (str.length == 0) {
document.getElementById("livesearch").innerHTML = "";
document.getElementById("livesearch").style.border="0px";
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) {
document.getElementById("livesearch").innerHTML=this.responseText;
document.getElementById("livesearch").style.border="0px solid";
}
}
xmlhttp.open("GET","php/ajaxphpfile.php?q="+str,true);
xmlhttp.send();
}
The html file-
<input type="text" class="search-query form-control" onkeyup="showHint(this.value)" id="type" name="name"placeholder="Search" />
<button type="submit" name="submit" value="oldsearch" class="btn btn-danger" type="button"></button>
<div id="livesearch"></div>

Related

Pass a current page's php variable through to XMLHttpRequest2 (i.e. $user_id)

I am trying to figure out if a current page's php $var can be passed through to the XMLHttpRequest2. The file that is being called is located outside of the views(where the current php page is located) folder in the /assets/js directory. I am using CodeIgniter as well. Trying to pass the $user_id along to use in a SQL query in side the XMLHttpRequest2 requested file.
publication_call.php (current file)
<form>
<input type="hidden" id="someid" value="<?= $idz ?>"/>
<?php
echo form_label('Validation: (Enter Publication keywords, Matches will appear in Dropdown > )');
echo form_label('Matching<br>Publications:');
?>
<select name="matched_pub" id="matched_pub"></select>
</form>
<script>
jQuery(function($){
//still want to bind the change event
$('#matched_pub').bind('change', function(){
$('#title').val($('#matched_pub option:selected').text());
});
$('#validation').keyup(function() {
showKeywords( $('#validation').val() );
document.getElementById('matched_pub').style.display='block';
});
});
</script>
<script>
function showKeywords(str)
{
if (document.getElementById("matched_pub")) {
if (str.length==0)
{
document.getElementById("matched_pub").innerHTML="";
document.getElementById("matched_pub").innerHTML=xmlhttp2.responseText;
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp2=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp2=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp2.onreadystatechange=function()
{
if (xmlhttp2.readyState==4 && xmlhttp2.status==200)
{
document.getElementById("matched_pub").innerHTML=xmlhttp2.responseText;
}
}
xmlhttp2.open("GET","/assets/keywordsearch.php?b="+str,true);
xmlhttp2.send();
}
}
</script>
searchwords.php (requested/external file)
<?php
$user = 'root';
$pass = 'root';
$db = 'hey_there';
$host = 'localhost';
$conn = mysql_connect($host, $user, $pass);
$db_selected = mysql_select_db($db, $conn);
//trying to display special chars
mysql_query("set names 'utf8'");
if(!$db_selected) {
echo 'broke';
}
//echo 'db connected';
$q = $_GET["b"];
//explode and parse $q into all the fragments separated by spaces and do full text search +word1 +word2 +word3, this will ignore HTML tags as it ignores word order, will also solve the middle initial problem [db setup is not compatible with full text search, but can do likes per word, less efficient, but how it must be done]
$queryWords = explode(' ', $q);
//for services query, explode the query into words and search for each separately
$query = "SELECT DISTINCT(pub_title)
FROM teacher_publications
JOIN users ON teacher_publications.user_id = users.id
WHERE keywords IS NOT NULL
AND pub_title IS NOT NULL
AND teacher_publications.user_id = 103 <-- $var will go here
";
$queryServicesLoop = '';
$queryServicesEnd = ' ORDER BY pub_title ASC';
//loop through all words in string
foreach($queryWords as $queryWord) {
$queryServicesLoop .= " AND (keywords LIKE '%{$queryWord}%')";
}
$queryServices = $queryServices.$queryServicesLoop;
$queryServices = $queryServices.$queryServicesEnd;
$resultServices = mysql_query($queryServices);
$services ='';
if(mysql_num_rows($resultServices) > 0){
while($rowServices = mysql_fetch_assoc($resultServices)) {
$services .= '<option value="' . $rowServices['pub_title'] . '">' . $rowServices['pub_title'] . '</option>';
}
}
if( mysql_num_rows($resultServices) == 0 )
{
echo '<option value="">Your search failed to find any matching results.</option>';
}
else
{
echo '' . $services . '';
}
/* ==============================
Edited Code
============================== */
publication_call.php (current file)
<input type="hidden" id="someid" value="<?= $user_id ?>"/>
<script>
function showKeywords(str)
{
if (document.getElementById("matched_pub")) {
if (str.length==0)
{
document.getElementById("someid");
document.getElementById("matched_pub").innerHTML="";
document.getElementById("matched_pub").innerHTML=xmlhttp2.responseText;
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp2=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp2=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp2.onreadystatechange=function()
{
if (xmlhttp2.readyState==4 && xmlhttp2.status==200)
{
document.getElementById("matched_pub").innerHTML=xmlhttp2.responseText;
}
}
xmlhttp2.open("GET","/assets/keywordsearch.php?b="+str+"&user_id="+document.getElementById('someid'), true);
// xmlhttp2.open("GET","/assets/keywordsearch.php?b="+str,true);
xmlhttp2.send();
}
}
</script>
searchwords.php (requested/external file)
$usr = $_GET["user_id"];
$query = "SELECT DISTINCT(pub_title)
FROM teacher_publications
JOIN users ON teacher_publications.user_id = users.id
WHERE keywords IS NOT NULL
AND pub_title IS NOT NULL
AND teacher_publications.user_id = ".$usr."
";
You can put $user_id inside of a hidden input field, and using Javascript, read the value of it to use in your Ajax request
You can do it like this:
<input type="hidden" id="someid" value="<?= $user_id ?>
And then after you've done that, you can get the value by doing this:
document.getElementById('someid'); using plain Javascript or $('#someid').value(); if you use jquery
This will get you the user ID value which you can then use in the request.
Like so:
xmlhttp2.open("GET","/assets/keywordsearch.php?b="+str+"&user_id="+document.getElementById('someid').value, true);
Replace your current xmlhttp2.open with the one above
Now you can access the value of user ID in $_GET['user_id'] in the requested file.

Using AJAX, PHP and MySQL to display table data

I would like to display one column of data, [pin], based on the [plan] and [order_id] values. plan=9 and order_id=0. Would like to load data without reloading page, using ajax.
Here is my HTML/Script:
<script>
function showPins(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 (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getPins.php?q="+str,true);
xmlhttp.send();
}
}
</script>
HTML:
<div align="center">
<h3>View PIN's</h3>
<form>
<select name="users" onchange="showPins(this.value)">
<option value="">Select Plan Type:</option>
<option value="1">Plan1</option>
<option value="2">Plan2</option>
<option value="3">Plan3</option>
</select>
</form>
<br/>
<div id="txtHint"></div>
</div>
This is my PHP file (getPins.php):
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('myHost','myUsername','myPw','my_db');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"my_db");
$sql="SELECT * FROM attPins WHERE (order_id=0, plan=9 and id = '".$q."')";
$result = mysqli_query($con,$sql);
echo "<table>
<tr>
<th>PIN's</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['pin'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
This is based off the tutorial shown here: http://www.w3schools.com/php/php_ajax_database.asp
Trying to make it work for showing the correct pins for plan type chosen.
your query would be wrong read manual where
$sql="SELECT * FROM attPins WHERE (order_id=0, plan=9 and id = '".$q."')";
It would be
WHERE (order_id=0 and plan=9 and id = '".$q."')
Or
WHERE (order_id=0 OR plan=9 and id = '".$q."')
according to your requirment

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

How to pass two php variables in JavaScript function

This is my code for fetching values from DB in a Table.
After fetching values I'm simply taking the ID of user in function to Activate and Deactivate that user.
<?php
$sql = "SELECT * FROM registration";
$result = mysqli_query($con, $sql);
while ($test = mysqli_fetch_array($result)) {
$id = $test['id'];
$status = $test['status'];
echo "<tr align='center'>";
echo"<td><font color='black'>".$test['username']."</font></td>";
echo"<td><font color='black'>".$test['firstname']." " .$test['lastname'] .
"</font></td>";
echo"<td><font color='black'>" . $test['status'] . "</font></td>";
echo"<td><a id='link' onclick=\"activate(" . $id . ");\">Activate</a></td>";
echo"<td><a id='link' onclick=\"deactivate(" . $id . ");\">Deactivate</a></td>";
echo "</tr>";
}
?>
Now, this is my AJAX code for activate()
function activate(item)
{
var id = item;
if (confirm("Do you wants to Activate user"))
{
$("#wait").css("display", "block");
var id = item;
var status = status;
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)
{
window.location.reload();
}
}
xmlhttp.open("GET", "php/update_act.php?id=" + id + "&req=activate", true);
xmlhttp.send();
}
}
I want to write or update the activate function so that,
I will get the current status of the user so that I'll check if the User is already Activated or not.
And if user is already Activated it should prompt me that this user is already activated else I should be able to Activate the User.
I assume you want to pass $status in the function as well so you can do something as
In Php code
echo '<td><a id="link" onclick="activate(\''.$id.'\',\''.$status.'\');">Activate</a></td>';
And you can change the JS function signature as
In Javascript
function activate(yourItem,uStatus){ }

window.XMLHttpRequest combine with script .change

I have a problem with combinning two scripts.
Fisrt script is working perfectly and taking stuf from mysql:
<script type="text/javascript">
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','includes/test-search.php?q='+str,true);
xmlhttp.send();
}
</script>
The second one is working perfectly and it's simple script for inserting data after change:
<script type="text/javascript">
$("document").ready(function(){
$("#selection").change(function () {
$("#someDivName").html( $("#selection option:selected").val() );
});
});
</script>
now the hole point is to combine them.
It's look like, when I load the site it don't have id selection and second script stops but after taking data from php and mysql file test-search.php the missing id selection is on site but the first script is not checking if id selection apear and don't work.
The php code:
<?php
$q=$_GET["q"];
$con = mysql_connect('localhost', 'root', '');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("table", $con);
$sql="SELECT * FROM prod_models WHERE prod_main_group_id = '".$q."'";
$result = mysql_query($sql);
echo '
<select id="selection" name="prod_main_group_id" onchange="change_val()">
<option value="">Wybierz produkt</option>
';
while($row = mysql_fetch_array($result))
{
echo '<option value="'.$row['id'].'">';
echo $row['product_name'] . "</option>";
}
echo "</select>
";
mysql_close($con);
?>
Code to display changed script:
<input type="text" id="someDivName" value="" />
if any one can help with solving the problem will be realy nice.
Thx i'm waiting for it now and trying to solve this for my self but now I don't have other ideas for it.

Categories

Resources