Auto complete multiple results in textfield from mysql database [closed] - php

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am new in php and ajax. I have search a lot from internet for this problem but in vain. I want to make an auto complete system just like this website: (http://www.zameen.com/). My problem is more simple than this website. My requirement is: "When I will enter something in text field, it will show the match results from database. When i will select one of those results then it will show in the same text field. I want to select multiple results and all results will show in the same text field."
Now my next question is: "how i will handle all these results in php variables and post them to my required file."
I am so much confused. Please give a simple solution because I am new in php and ajax.
You can see an image to understand my problem on this link: (http://mutaliapakistan.com/problem.png).

I'll try to give you a simple, working example of what you want:
this will be your livesearch.js file:
function showResult(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 (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("livesearch").innerHTML=xmlhttp.responseText;
document.getElementById("livesearch").style.border="1px solid #A5ACB2";
}
}
xmlhttp.open("GET","livesearch.php?q="+str,true);
xmlhttp.send();
}
And this will be your livesearch.php file:
<?php
$hint="";
//get the q parameter from URL
if (!isset($key))$key = $_GET['q'];
//include the mysql conn script
require_once ('mysql_connect.php');
//just change the selects here to what you want/ need.
$query = "SELECT DISTINCT * FROM table_name WHERE display='1' AND (name LIKE '%$key%' OR description LIKE '%$key%') LIMIT 5";
$result = mysql_query($query);
while($result_row = mysql_fetch_array($result))
{
$found = $result_row[12];
if (strlen($found)>25)
{
$found = substr($found, 0, 25) . '...';
}
$hint = $hint."<div id='search_result'>".$found."</div>";
}
// Set output to "no suggestion" if no hint were found
// or to the correct values
if ($hint == "")
{
$response = "No results";
}
else
{
$response = $hint;
}
//output the response
echo $response;
?>
And now finally to the page that you want to have the seach in it add the following:
<script type="text/javascript" src="livesearch.js"></script>
<div class="search">
<form name="frm_search" id="frm_search" method="get" action="advanced_search.php">
<input type="text" name="search" id="search" value="" placeholder=" Search" onkeyup="showResult(this.value)"/>
<input type="submit" name="search_go" id="search_go" value="↵"/>
</form>
<div id="livesearch" style="margin-left:3px;background-color:#fff;text-align:left;">
</div>
</div>
I hope it's clear.

Related

jQuery data sent from PHP is not the correct format?

I am using jQuery to send a part number from one php file to another.
The part number is received correctly in the destination php file, but when when I try to use it, it does not work.
Here is the strange thing: To test,when I use $mpn=STA-12 (or any other value that exists in table2), in destination php file, the connection is established and the relevant data is extracted, BUT when THE SAME DATA is fetched, it does not work
Here is the destination PHP file:
<?php
$row['mpn'] = $_GET['q'];
include("order/connection.php");
echo "mpn is here : ".$row['mpn']; // It displays STA-12 but doesn't data get fetched!
$mpn=$row['mpn'];
//$mpn="STA-12"; // *** When I actually put this line in, it all works ***
$stmt = $pd->prepare("SELECT * FROM table2 WHERE part_number = :part_number " );
//$stmt->execute(array());
$stmt->execute(array(':part_number' => $mpn));
$row = $stmt->fetch(PDO::FETCH_BOTH);
//... rest of the code
?>
This jQuery script copied from W3:
<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","serv.reply3.3.php?q="+str,true);
xmlhttp.send();
}
}
And this is where it is called from:
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Choose</option>
<option value=" <?php echo $row["mpn"]; ?> ">items</option>
</select>
</form>
The problem is finally solved.
Since the code was copied from another example, the jQuery variable sent over, contained some EXTRA information that when ECHO'ed didn't show.
echo "mpn is here : ".$row['mpn']; that displayed STA-12, actually contained ' string(6) " STA-12" ', which was discovered by doing:
var_dump( $row['mpn']).
This had my head scratching for days.

ajax/php not able to edit files

I'm developing a web page that should read and change the contents of specific files on the server.
These files will only have two values: 1 or 0. Reading/changing the contents will be made via combo boxes with OnChange. Basically the idea is to control appliances via General Purpose Input/Outputs (GPIO's). The electronics part is all done, I just need to finish the web programing part and got stuck on it.
I'm not experienced in programing at all, but with some snippets found here and there, I was able to implement part of it with AJAX/PHP.
So far, I'm able to read the values, but unable to change it even though I'm building the correct command with "escapeshellarg".
Also, I was expecting to have two interactive areas in the page but only the original is working.
Could anyone point me into the right direction? Any help/suggestion/comment will be welcomed.
pqp6.php
<html>
<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","getinfo.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<?php
$file1="/var/www/file1";
$file2="/var/www/file2";
$output = shell_exec('cat '.escapeshellarg($file1));
if($output == 0)
{
echo "zero ; ";
$file1status = "off";
$file1oposite = "on";
$file1exec= "file1on";
}
else
{
echo "one ; ";
$file1status= "on";
$file1oposite= "off";
$file1exec= "file1off";
}
echo "output:$output ; file1status:$file1status ; file1oposite:$file1oposite ; file1exec:$file1exec <br><br>";
$output = shell_exec('cat '.escapeshellarg($file2));
if($output == 0)
{
echo "zero ; ";
$file2status = "off";
$file2oposite = "on";
$file2exec= "file2on";
}
else
{
echo "one ; ";
$file2status= "on";
$file2oposite= "off";
$file2exec= "file2off";
}
echo "output:$output ; file2status:$file2status ; file2oposite:$file2oposite ; file2exec:$file2exec <br><br>";
?>
<br>
<br>
FILE 1:
<form>
<select name="file1" onchange="showUser(this.value)">
<option value="1,<?=$file1status?>"><?=$file1status?></option>
<option value="1,<?=$file1oposite?>"><?=$file1oposite?></option>
</select>
</form>
<br>
<div id="txtHint"><b>File 1 information will be listed here.</b> </div>
<br>
<br>
FILE 2:
<form>
<select name="file2" onchange="showUser(this.value)">
<option value="2,<?=$file2status?>"><?=$file2status?></option>
<option value="2,<?=$file2oposite?>"><?=$file2oposite?></option>
</select>
</form>
<br>
<div id="txtHint"><b>File 2 information will be listed here.</b></div>
</body>
</html>
getinfo.php:
<?php
$q=$_GET["q"];
$q_stripped = explode(",", $q);
$file_n = $q_stripped[0];
$file_command = $q_stripped[1];
$path="/var/www/file";
if($file_command == "on")
{
$file_command = "1 > ";
}
else
{
$file_command = "0 > ";
}
$command= "/bin/echo $file_command$path$file_n";
$escaped_command = escapeshellarg($command);
echo "COMMAND: $escaped_command";
shell_exec($escaped_command);
echo "file_n=$file_n ; file_command=$file_command ; ";
?><?php
By applying the escapeshellcmd your > 0 or > 1 is turned into \\> 0 and \\> 1 I guess that is why it doesnt work. You are not using escapeshellcmd, you are using escapeshellarg.
You might want to check the file permissions also.
However, instead of using system calls, have you ever thought about using
file_exists, file_get_contents or file_put_contents .
With those functions and writable dirs/files, you can achieve exactly what you are doing, without making system calls. Plus, it would be more portable.

use one text field to search database, then pupulate remaining fields in PHP

I'm new here, so I hope this makes sense I am new to PHP and Ajax...so I am quite lost.
I have a MySQL database setup, and several forms created in PHP. I have several text fields on one of the forms, which is supposed to show customer info. The first text (phone #) field is supposed to be a search field ... so I need to query my database once the user finishes entering the phone #, to find the records and populate the remaining fields.
I've tried various ways of doing this...but nothing comes out quite right! The method which seems to show the most promise is by using the Onblur event to call a php page (using Ajax) which will perform the search.
This works, in that I can query the database to find the results .. and have them displayed back. The trouble is that this page with the data inside is actually displayed in the middle of my first page ...so basically I have one web page displaying inside the other...which is obviously not what I want.
The basic code I have is:
HTML side --
<script>
function showUser(str) {
if (str == "") {
document.getElementById("divider").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) {
document.getElementById("divider").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "GetCustomer.php?q="+str, true);
xmlhttp.send();
}
</script>
</head>
<label for="CustPhone">Phone:</label>
<input type="text" name="CustPhone" id="CustPhone" tabindex="1" onchange="showUser(this.value)" value="<?php ?>">
<br>
<div id="divider"></div>
<label for="CustLastName">Last Name:</label>
<input type="text" name="CustLastName" id="CustLastName" tabindex="2" value="<?php echo $clast; ?>">
<label for="CustFirstName">First Name:</label>
<input type="text" name="CustFirstName" id="CustFirstName" tabindex="3" value="<?php echo $cfirst; ?>">
<p> </p>
<label for="CustAddress1">Address 1:</label>
<input type="text" name="CustAddress1" id="CustAddress1" tabindex="4" value="<?php echo $caddr1; ?>">
<label for="CustAddress2">Address2:</label>
<input type="text" name="CustAddress2" id="CustAddress2" tabindex="5" value="<?php echo $caddr2; ?>">
<p> </p>
and the PHP --
include ("AddEdit.php");
require_once("customer_info.php");
function LoadData()
{
$pn = $_POST['CustPhone'];
if (strlen($Pn) < 10)
{
$query = "SELECT * FROM customer WHERE Phone='$Pn'";
$result = mysql_query($query);
if (!$result) die ("Database access failed: " . mysql_error());
$rows = mysql_num_rows($result);
$rowinfo = mysql_fetch_array($result);
if ($rows > 0)
{
$clast = $rowinfo['LastName'];
$cfirst = $rowinfo['FirstName'];
$caddr1 = $rowinfo['Address1'];
$caddr2 = $rowinfo['Address2'];
$ccity = $rowinfo['City'];
$cprov = $rowinfo['Province'];
$cpostal = $rowinfo['Postal'];
}
}
}
Any ideas as to how I can do this without jumping around as much ... or more importantly just show the data on the existing page, rather than showing a smaller version of my entire page within the page ??
Thx!!!
I will recommend to use Jquery Ajax, more simple and easy way for Ajax.
For more details, refer Jquery Ajax.
So you can change your Ajax call as follows :
$.ajax({
type: "POST",
url:"GetCustomer.php",
data: "q="+str,
success : function(data) {
//do someting with your data
}
}
});
With this you can handle error state as well as display "in progress" bar while the Ajax call is in progress.
In success you need to map your data with the fields in form instead of displaying them inside a div. This is the only thing you are missing in your approach. So instead of following line -
document.getElementById("divider").innerHTML = xmlhttp.responseText;
add JS code to map the data with the fields.
You can use JSON datatype and easily map the data with your forms.
First, I recommend to use jQuery ajax instead of old ajax.
I Think your result are not in the correct place because you are using "innerHTML" in this line of code
document.getElementById("divider").innerHTML = xmlhttp.responseText;
so your results will be there.

ajax issue in zencart

I have some main categories and subcategories of each main category..I've a dropdown list contains main category, when i choose a main category then the subcategory dropdown list shows the subcategories of that main category..
am using the following code for this, but this shows the subcategory box contains the whole page with header and footer...
<select name="main_category" id="main_category" onchange="showSubCategory(this.value)">
<option>--Select--</option>
</select>
<script type="text/javascript">
function showSubCategory(str)
{
if (str.length==0)
{
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)
{
alert(xmlhttp.responseText);
document.getElementById("subcategory").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","index.php?main_page=getsubcategory&cid="+str,true);
xmlhttp.send();
}
</script>
in tpl_subcategory_default.php contains
<?php
$cid=$_GET['cid'];
$sql="select cd.categories_name, cd.categories_id
from " . TABLE_CATEGORIES . " c, " . TABLE_CATEGORIES_DESCRIPTION . " cd
where c.parent_id = '" . (int) $_GET['cid'] . "'
and c.categories_id = cd.categories_id
and c.categories_status= 1";
$r=mysql_query($sql);
while($row=mysql_fetch_array($r))
{
echo "<option value=$row[categories_id]>$row[categories_name]</option>";
}
?>
It's showing the whole page with header and footer because you're accessing the "page" via index.php?main_page=foo but haven't added architecture to replace the normal templating system outputs with your own page-specific output ... ie: to jump directly to the output without first calling the normal things which appear on every page.
Your question can't really be accurately answered without knowing also what you've done in the /includes/modules/pages/subcategory/header_php.php file, or if you've even created one. Chances are that the code you've put into tpl_subcategory_default.php could go into the header_php.php file mentioned above, followed by a die() statement at the end, and accomplish the same thing which you seem to be looking for.
It would be easier to answer your question fully if you supplied more information about what you've done so far.
To remove header,footer etc you can override the tpl_main_page.php. Go to this directory /includes/templates/custom template. As per your information you have created main_page=getsubcategory page. so create a folder named getsubcategory under this directory. then copy tpl_main_page.php from includes/templates/custom template/common/ and paste it in /includes/templates/your custom template/getsubcategory. Then do the below changes in tpl_main_page.php file.
if (in_array($current_page_base,explode(",",'getsubcategory')) ) {
$flag_disable_left = true;
$flag_disable_header = true;
$flag_disable_footer = true;
}

How to prevent the page from scrolling after an ajax request (return false not working or maybe in the wrong palce)

I want to display a tree with information about the Catalogue of Life which includes the Kingdom, phylum, order, etc information. I'm using ajax/php to interact with a mySQL database, while using javascript to display and output the information. I have finally completed the things I wanted it to do: expand and collapse on clicking, load only once, etc. But everytime something is clicked below the scroll limit, it bounces back to the top of the page. I researched this and saw something about including 'return false' in the function or the tag, but this did not solve the problem. Am I just putting it in the wrong place? Thanks for your help...
Here is the code: in its php/javascript goodness...
<?php
include ('includes/functions.php');
$connection=connectdb();
$result=runquery('
SELECT scientific_name_element.name_element as shortname ,taxon_name_element.taxon_id as taxonid
FROM taxon_name_element
LEFT JOIN scientific_name_element ON taxon_name_element.scientific_name_element_id = scientific_name_element.id
LEFT JOIN taxon ON taxon_name_element.taxon_id = taxon.id
LEFT JOIN taxonomic_rank ON taxonomic_rank.id = taxon.taxonomic_rank_id
LEFT JOIN taxon_name_element AS tne ON taxon_name_element.parent_id = tne.taxon_id
LEFT JOIN scientific_name_element AS sne ON sne.id = tne.scientific_name_element_id
LEFT JOIN taxon AS tax ON tax.id = tne.taxon_id
LEFT JOIN taxonomic_rank AS tr ON tr.id = tax.taxonomic_rank_id
WHERE taxon_name_element.parent_id is NULL');
set_time_limit(0);
ini_set('max_execution_time',0);
?>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.js"></script>
<script type="text/javascript">
function load_children(id){
if(document.getElementById(id).active != 'true'){
if(document.getElementById(id).loaded != 'true'){
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()
{//actual stuff
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{//change the text
this.active='true'
//document.getElementById(id).innerHTML = xmlhttp.responseText;
var oNewNode = document.createElement("ul");
document.getElementById(id).appendChild(oNewNode);
document.getElementById(id).active = 'true';
document.getElementById(id).loaded = 'true';
oNewNode.innerHTML="<i>"+xmlhttp.responseText+document.getElementById(id).active+"</i>";
}
}
xmlhttp.open("GET","new.php?id="+id,true);
xmlhttp.send(false);
}else{
$("#"+id).children().children().show(); document.getElementById(id).active = 'true'}}else{ $("#"+id).children().children().hide();
document.getElementById(id).active = 'false';
}return false;}
</script>
</head>
<body>
<?php
echo "<ul>";
while($taxon_name_element = mysql_fetch_array($result)){
echo "
<li id=\"{$taxon_name_element['taxonid']}\" style=\"display:block;\">{$taxon_name_element['shortname']}</li>
";}
echo "</ul></body></html>";
?>
You were missing a closing parenthesis - if popped it in with a comment where I think you were wanting it. If JS has an error it generally won't execute, and instead it'll fall back to the non JS (ie, the return false wont fire because of the error). Were you getting an actual error when running this? The console is a good friend when you're debugging JS.
Formatting your code like I have below will also help to identify any missing elements more easily.
function load_children(id)
{
if(document.getElementById(id).active != 'true')
{
if(document.getElementById(id).loaded != 'true')
{
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()
{
//actual stuff
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//change the text
this.active='true'
//document.getElementById(id).innerHTML = xmlhttp.responseText;
var oNewNode = document.createElement("ul");
document.getElementById(id).appendChild(oNewNode);
document.getElementById(id).active = 'true';
document.getElementById(id).loaded = 'true';
oNewNode.innerHTML="<i>"+xmlhttp.responseText+document.getElementById(id).active+"</i>";
}
}
xmlhttp.open("GET","new.php?id="+id,true);
xmlhttp.send(false);
} // This was missing - were you getting an error?
}
else
{
$("#"+id).children().children().show(); document.getElementById(id).active = 'true'}
}
else
{
$("#"+id).children().children().hide();
document.getElementById(id).active = 'false';
}
return false;
}
When you're done checking and if everything is ok, take a look at: http://api.jquery.com/jQuery.get/ - the example's are at the bottom.

Categories