No output in Autocomplete - php

I use autocomplete to achieve a Google like search where the search suggestions are in a dropdown while i type what i'm searching for.
The Output of my code
HTML
<td width="155" bgcolor="#999999">Client Name</td>
<td width="218" bgcolor="#999999"><input type="text" name="clientname" id="clientname" class="forinput" /></td>
script
<script type="text/javascript">
$(document).ready(function() {
$( "#clientname" ).autocomplete(
{
source:"getautocomplete.php",
minLength:1
})
});
</script>
getautocomplete.php
..databaseconnection
$term = trim(strip_tags($_GET['term']));//retrieve the search term that autocomplete sends
$qstring = "SELECT clientname FROM client WHERE clientname LIKE '%".$term."%'";
$result = mysql_query($qstring);//query the database for entries containing the term
while ($row = mysql_fetch_array($result,MYSQL_ASSOC))//loop through the retrieved values
{
$row['clientname']=htmlentities(stripslashes($row['clientname']));
$row_set[] = $row;//build an array
}
echo json_encode($row_set);//format the array into json data
What i want to achieve
I check my database connection and its correct. Can anybody explain to me what I'm doing wrong? did i missed something?

I don't think the result you are sending back is valid according to what jQueryUI is expecting.
Now you are building an array of arrays and you should only send the values back (assuming that the label and the value are the same, the name of the client):
// $row['clientname']=htmlentities(stripslashes($row['clientname']));
$row_set[] = htmlentities(stripslashes($row['clientname'])); //build an array
Also note the comments about the deprecated mysql_* functions and sql injection.

Related

Hello i'm trying to do multiple sorting using php mysql where i'm searching and then sorting the data

i'm printing a table in php where data is coming from mysql now i'm creating functionalities like searching and sorting so when i click on sort it sorts the data and when i click on search i get searched data now the problem is i want to perform sorting on searched data like for example i sorted the data and then i searched for words starting with a i.e i got results like adam,azan,anand so i want to perform resorting on these searched data and get data as adam,anand,azan
my approach is:
<?php
if(isset($_GET['search_btn'])){
$search=$_GET['search'];
$result=GetWords(mysqli_escape_string($conn,$search));
}
/*if(isset($_GET['q'])){
$id=$_GET['q'];
$result=GetWordsById($id);
}*/
if(isset($_GET['sort'])){
$sort=$_GET['sort'];
}
if(isset($_GET['sort'])){
if($sort=="asc"){
$result=SortContent();//Here Get Sort Content is a function calling Store Procedure SortContent which is working at first sorting
}
if($sort=="desc"){
$result=SortContent2();
}
}
else{
$result=GetAdminWords();
}
if(mysqli_num_rows($result)>0)
?>
<thead>
<tr>
<th>Word</th>
<th>Meaning</th>
<th>Synonym</th>
<th>Antonym</th>
</tr>
</thead>
<?php
while($row=mysqli_fetch_array($result)){
?>
<tbody>
<tr>
<td><?php echo $row['word'];?></td>
<td><?php echo $row['meaning'];?></td>
<td><?php echo $row['synonym'];?></td>
<td><?php echo $row['antonym'];?></td>
<td><i class="fa fa-edit"></i> <a onClick="javascript: return confirm('Please confirm deletion');" href="view.php?id=<?php echo $row['id'];?>"><i class="fa fa-trash"></i></a> </td>
</tr>
</tbody>
<?php
}?>
and i'm talking in context of large amount of data i hope i have made myself clear and if possible how can i implement ajax using mysqli
You will need to trigger an event in JavaScript, which in turn will use your HTML search input, which is then sent to the server, where a query will be executed and the results returned (as HTML) to the JavaScript code, and finally placed back on the page. At least this is how I solve my ajax searches...
So the flow could be something like:
Input -> JavaScript event -> ajax -> result -> page
Here is some code that might get you started, though I haven't tested i myself:
HTML:
<input type="text" id="my_search_input">
<div id="my_search_result"></div>
JS (jQuery):
var $inputField = $( "#my_search_input" );
var $result = $( "#my_search_result" );
$inputField.on('keyup', function(){ //triggered when a pressed key is lifted
var searchTerm = $inputField.val();
$.ajax({
url:"/mySearch.php",
method:"post",
data:{searchTerm:searchTerm},
success:function(response){ //response contains the data from mySearch.php
var parsedResponse = JSON.parse(response);
var resultHtml = parsedResponse.html; //this is the array key of what the PHP script returns
$result.append(resultHtml);
}
});
});
PHP
$searchTerm = $_POST['searchTerm']; //$_POST['searchTerm'] is what we defined in data:{... in the ajax call
// here is where you need to retrieve data from your database
// the db result needs to be processed into HTML and assigned to a variable
$html = "<div>My result based on data</div>";
return json_encode(['html' => $html]);

AJAX json_encode returning [object Object]

Okay, so I'm a bit of a newb to JSON. I'm trying to cobble together an AJAX call(a PHP mssql query) that returns the values back to the original form through JSON. I'm getting [object Object] instead of the actual value of the variable. Through some searching I think the issue is related to parsing, but I thought json_encode handled this. Or maybe it does and I haven't structured this correctly.
Here's what Im trying to accomplish:
An html form has 3 fields: Account Number, Account Name and Address1. I want the user to be able to enter the Account Number and then have the Name and Address fields populate on blur with the results of the mssql query.
Here's what I have:
HTML
<body>
<label>Account Number:</label><input type="text" id="acctnumber" />
<label>Account Name:</label><input type="text" id="acctname" />
<label>Address 1:</label><input type="text" id="address1" />
</body>
Jquery (I put the acctnumber input value in just for testing)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#acctnumber").blur(function(){
$.ajax({
url: "ajaxtestscript.php?acctnumber=hfi01",
dataType: "json", //the return type data is jsonn
success: function(data){ // <--- (data) is in json format
$("#acctname").val(data.Name);
$("#address1").val(data.Address);
//parse the json data
}
});
});
});
</script>
PHP
<?php
header('Content-Type: application/json');
//mssql connection info//
$acctnumber = $_GET["acctnumber"]; // we received this from the json call
//declare the SQL statement that will query the database
$query = "select[description],[daddr1] from trCustomer where company = '$acctnumber' and archived = 0";
//execute the SQL statement and return records
$rs = $conn->execute($query);
$test = array();
$test['Name'] = $rs[description];
$test['Address'] = $rs[daddr1];
echo json_encode($test);
//echo $name.$address; put this in to test the query was working, which it was
//close the connection and recordset objects freeing up resources
$rs->Close();
$conn->Close();
$rs = null;
$conn = null;
?>
When I actually try this on the html form, I enter in the Account number value (hardcoded at this point) and click out of the element to fire blur, and in the other two input fields I get [object Object]. Although if I just echo my query back I can see the values so I'm thinking I have done something wrong or left something out with my json_encode. Any assistance would be greatly appreciated.
After executing your query, you first need to fetch the resulting rows with whatever function your DB Library is supposed to do so. And should't you prepare your query first?
Otherwise the object that you are trying to json_encode() is an resource object. That is why you get object Object. I would expect code like this
$conn = new PDO(...);
$stmt = $conn->prepare("SELECT ...");
$stmt->execute();
$test = array();
while ($row = $stmt->fetch()) {
$test[] = array(
'Name' => $row[description],
'Address' => $row[daddr1]
);
}
echo json_encode($test);
$stmt = NULL;
$conn = NULL;
First of all, your question is unclear and depending on the situation, I would debug and test the outputs.
1. PHP : The query result : var_dump(json_encode($test)); exit(0);
This will help you to know what data is being sent to front. alert or console print the received data in ajax to view.
2. Javascript : console.log(data);
This will help you to know what data is being received and what exactly you need to write to populate in the required field. Check in browser console.
Thanks for upvoting. Cheers !

Populate input with database data on select change

I'm an absolute beginner in the HTML/Php/JavaScript world. I'm trying to make this page:
dropdown list with titles of documents
when something is selected, populate input fields below with data from PostgreSQL to allow for update
submit button to update database with corrected values from user.
1 and 3 are ok (already tried this with an insert-only form).
My code looks like this (simplified, without dbconn):
echo "<select name='listedoc' size=1>";
while ($ligne = pg_fetch_array($result, null, PGSQL_ASSOC))
{
echo '<option value="'.$ligne['id_doc'].'">'.$ligne['doc_titre']. '</option>';
}
echo "</select>";
The input fields (simplified, there are 4 fields actually):
<p><form name="saisiedoc" method="post" action="docupdins.php"></p>
<table border=0>
<tr><td>Texte</td>
<?php
echo '<td> <textarea name="content" cols="100" rows="30"></textarea> </td>';
?>
</tr><tr>
<td colspan=2>
<input type=submit value="Valider la saisie" name="maj"> </td>
</tr>
</table>
</form>'
Then JQuery script :
<script>
$(document).ready(function(){
$("select#listedoc").change(function () {
var id = $("select#listedoc option:selected").attr('value');
$.post("docsel.php", {id:id},function(data) {
});
});
</script>
The php to select fields (docsel.php):
<?php
include('../scripts/pgconnect.php');
$iddoc = $_POST['id'];
$sql="SELECT * FROM document where id_doc = $iddoc";
$result = pg_query($db, $sql);
if (!$result) {
echo "ERREUR<br>\n";
exit;}
$row = pg_fetch_row($result);
$doctyp = $row[1];
$doctitre = $row[2];
$docauteur = $row[3];
$doccontent =$row[4];
pg_free_result($result);
pg_close($db);
}
?>
Whatever I do, I can't get back values. I tried value="'.$doctitre'" in the input,
echo $doctitre, to no avail . Is my code logic correct ? Thank you for your help
you are close. the script docsel.php needs to return the data to the html-page.
you have it already setup to receive the data in the callback function
$.post("docsel.php", {id:id},function(data) {
$('textarea[name="content"]').text(data.content);
});
in order to have something in data.content, the php script sends json data:
$result = [];
$result['content'] = $doccontent;
echo json_encode($result);
maybe you need to read the docs on $.post and json_encode... good luck.
There are a couple of things you need to change here.
Firstly, and most importantly your docsel.php script has a gaping security hole. You should never ever ever place unsanitised input e.g. directly from a user, straight into a SQL query because it allows for SQL injection. Essentially, SQL injection allows a malicious user to end the programmers query and submit their own. To get round this you must sanitise any user input - so in this case pass the user input through the function pg_escape_literal() before putting it into your query.
Secondly, your docsel.php script must put out some kind of output for the AJAX request. You can do this by using echo and I would recommend you encode it into JSON. Code example:
$return_vals = array("doctype" => $doctyp, "doctitle" => $doctitre, "docauthor" => $docauteur, "doccontent" => $doccontent);
echo json_encode(array("document" => $return_vals));
Lastly, in your jQuery script, you aren't actually doing anything with the data that is returned from your AJAX post request. Inside the callback function, you need to then add the returned fields to your select dropdown. Code example:
<script>
$(document).ready(function(){
$("select#listedoc").change(function () {
var id = $("select#listedoc option:selected").attr('value');
$.post("docsel.php", {id:id},function(data) {
//FILL THE DROPDOWN HERE
$(data).each(function(elem) {
$("#dropdown-id").append("<option value='" + elem.doctitle + "'>" + elem.doctitle + "</option>");
});
}, "json");
});
</script>
A mute and pedantic point, but when making requests for content then you should be using GET instead of POST.

jquery-ui-1.8.14 Autocomplete with php and mysql

I'm not very much into js and programing in general, but I'm very stuck on something that really shouldn't be too difficult. Feel free to visit the test page:
[REMOVED LINK]
I have three autocomplete fields: Current club, nation and career stats.
Autocomplete works perfectly for the career stats where I can also add fields and the autocomplete also works for the added field.
But for the current club and nation fields, I get results while typing but when I click the correct output it doesn't show up in the input-field.
I can make it work using other js-libraries, but then it no longer work for the add-button career stats fields.
I use the following libraries:
<script type="text/javascript" src="js/jquery-1.6.3.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.14.custom.min.js"></script>
<script type="text/javascript" src="js/jq-ac-script.js"></script>
The current club html looks like:
<p>
Current club <label>:</label>
<input type="text" id="currentclub" />
</p>
In the custom made jq-ac-script.js (I originally found this somewhere online - don't remember where) the important part is:
$(document).ready(function(){
$( "#currentclub" ).autocomplete({
source: "get_club_list.php",
minLength: 1
})
.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( item.currentclub )
.appendTo( ul );
};
});
The "get_club_list.php" looks like:
<?php
include ("dbsetup.php");
$return_arr = array();
$param = $_GET["term"];
$fetch = mysql_query("SELECT * FROM FootNews_CLUB
WHERE clubShortName LIKE '%$param%'");
/* Retrieve and store in array the results of the query.*/
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
$row_array['currentclub'] = $row['clubShortName'];
array_push( $return_arr, $row_array );
}
/* Free connection resources. */
mysql_close($conn);
/* Toss back results as json encoded array. */
echo json_encode($return_arr);
?>
Any ideas whereas to why the selected club doesn't show up when I click it would be appriciated!!
Wow, used my php code. Cool, glad I could help.
http://www.jensbits.com/2010/03/29/jquery-ui-autocomplete-widget-with-php-and-mysql/
Not sure why you are using the autocomplete code with _renderItem in it. I don't think you need it.
Change the php code to this:
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
$row_array['currentclub'] = $row['clubShortName'];
$row_array['value'] = $row['clubShortName'];
array_push( $return_arr, $row_array );
}
And, the jquery to:
$( "#currentclub" ).autocomplete({
source: "get_club_list.php",
minLength: 1
});
You can read through my tutorial again but the autocomplete needs a label or value field returned. It then populates the select list and the corresponding input field with that value.
I left in $row_array['currentclub'] = $row['clubShortName']; because I don't know if you are grabbing that later on. If you are not, you don't need that line either.
Since you control the returned data and can specify a label and/or value field in the php, I don't understand why you are using the _renderItem for any of the autocompletes.
BTW, you should add mysql_real_escape_string to your php code for some sql injection protection: http://www.php.net/manual/en/function.mysql-real-escape-string.php

Autocomplete form populated by a database?

I am currently working on a project in which I need to have an autocomplete form call its information from a db file. I have seen many tutorials on jquery autocomplete forms, but I do not know how to call a db file to populate the list.
I am working in PHP. Currently the code represents a simple drop down box that is calling on the db file for population.
<?php
global $wpdb;
$depts = $wpdb->get_results( "SELECT * FROM departments ORDER BY department_name ASC" );
echo '<select>';
foreach($depts as $row) {
echo '<option name="select_dept" value="'.$row->department_id.'">'.$row->department_name.'</option>';
}
echo '</select>';
?>
Any help would be awesome!
I recently have used this library for autocompletion - http://www.devbridge.com/projects/autocomplete/jquery/
So here is brief script based on yours:
<?php
$query = isset($_GET['query']) ? $_GET['query'] : FALSE;
if ($query) {
global $wpdb;
// escape values passed to db to avoid sql-injection
$depts = $wpdb->get_results( "SELECT * FROM departments WHERE department_name LIKE '".$query."%' ORDER BY department_name ASC" );
$suggestions = array();
$data = array();
foreach($depts as $row) {
$suggestions[] = $row->department_name;
$data[] = $row->department_id;
}
$response = array(
'query' => $query,
'suggestions' => $suggestions,
'data' => $data,
);
echo json_encode($response);
} else {
?>
<html>
<body>
<input type="text" name="" id="box" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script src="http://www.devbridge.com/projects/autocomplete/jquery/local/scripts/jquery.autocomplete.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#box').autocomplete({
serviceUrl:'/',
// callback function:
onSelect: function(value, data){ alert('You selected: ' + value + ', ' + data); },
});
});
</script>
</body>
<html>
<?}?>
Please follow this very well written tutorial
http://www.nodstrum.com/2007/09/19/autocompleter/
JQuery UI includes an autocomplete, although you still need to write a PHP script to return the information to be added to the control as its done via AJAX. If you know in PHP how to connect to a database, query it, and return a list of the results - then you will have no problems with this. JQuery makes AJAX extremely simple.
Depending on how complicated your field/data set is - and assuming its not millions upon millions of unindexed records, I would be content to autocomplete from a:
SELECT thing WHERE thing LIKE '".$query."%'
So if you were searching for, say, food... the query "CA" would pull out CArrot and CAbbage and CAuliflower. If you added a % to the beginning of the LIKE, you could get results that contained your query, as opposed to just beginning with it.
The page your user hits would contain the JQuery part which both sends the request and creates the autocomplete effect from the results, and a very simple, separate PHP script which the AJAX request hits would return the potential 'matches'.
Take a look at the Autocomplete demos on JQuery UI

Categories