Loading mysql rows from PHP into autocomplete jquery - php

<?php
$cuvant = (isset($_GET['cuvant']) ? $_GET['cuvant'] : '');
// the word I want to get from the search box
$sql = "SELECT cuvant FROM cautare where cuvant like'".$cuvant."%'ORDER BY nr_cautari DESC limit 0,6";
// I search for that word in a table from database
?>
<script>
$(function() {
var cuvinte=['<?php
$resursa = mysql_query($sql);
?>'];
$( "#cautare" ).autocomplete({
// #cautare is the id of the search box
source: cuvinte
});
});
</script>
I'm trying to make an auto-completer with jQuery, and I have this code in the index.php page. I don't know how to fix this issue: When I try to search something on the page, nothing happens.

Assuming that you are using jQuery Autocomplete: https://jqueryui.com/autocomplete/
I believe the variable that contains the values has to be valid JSON. Even doing an mysql_fetch_assoc() is going to return a php array that looks something like this for each row:
array(
'cuvinte' => "something"
);
So, assuming that there are multiple rows returned from your query, I think you would need to do something like this:
<script>
$(function() {
var cuvinte=
<?php
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) {
$resursa[] = $row['cuvant'];
}
echo json_encode($resursa);
?>;
$( "#cautare" ).autocomplete({// #cautare is the id of the search box
source: cuvinte
});
});
</script>
Basically, this takes the result of your query, loops through all the rows, and builds a temporary array. The last step is to take that array and let PHP turn it into json for you.

Related

jQuery UI autocomplete showing html code

I am having a problem with autocomplete that is confusing me a little. I did a search first, I am not the only one having this problem. But everyone seems to use jQuery Autocomplete in their own way, so it didn't really help me.
Anyway, here is the problem. I am building a search function, that is supposed to show a list of users, retrieved from a mysql database. I got that to work. So when I start typing, it immediately shows a list of users. What I want to do next, is to make the results links, that redirect the user to a different page.
Here is findartist.php;
if(isset($_GET['term'])){
$artist = new User();
$return_arr = array();
$results = $artist->findUser($_GET['term']);
foreach($results as $result){
$link = "<a href='profile/index.php?st=" . $result['stagename'] . "'/>" . $result['stagename'] . "</a>";
$return_arr[] = $link;
}
echo json_encode($return_arr);
}
And here is the jQuery;
<script>
$(function() {
//autocomplete
$(".artist_input").autocomplete({
source: "/includes/findartist.php",
minLength: 1
});
});
</script>
The problem is that when I do this, it shows the html code.
So this is what it would look like;
<a href='profile/index.php?st=bob'/>bob</a>
Is there a way to fix this?
This isn't how autocomplete is set-up to work. It's set up to assume what you return is the text you want to display. It can't handle HTML in the way you're asking.
However, that doesn't mean all is lost...
Instead of having findartist return an array of <a> tags, just the artist names.
Then, you write another function, bound to the 'select' event of the autocomplete object that will navigate you to the page you want.
See the documentation for the event in question here: http://api.jqueryui.com/autocomplete/#event-select
For example, findartist.php may change to:
if(isset($_GET['term'])){
$artist = new User();
$return_arr = array();
$results = $artist->findUser($_GET['term']);
foreach($results as $result){
$return_arr[] = $result['stagename'];
}
echo json_encode($return_arr);
}
And your autocomplete may look something like:
<script>
$(function() {
//autocomplete
$(".artist_input").autocomplete({
source: "/includes/findartist.php",
minLength: 1,
onSelect: function (suggestion) {
// event fires when the user selects something from the list.
window.location.href = "profile/index.php?st=" + suggestion;
}
});
});
</script>
Forgive me any mis-matched brackets or syntax error - I'm coding without a workign dev environment. Hopefully it helps anyway.
Try it out, see where you get.
you can work on form submit, it is the best way to redirected to results page
$(document).ready(function(){
$(".artist_input").autocomplete({
source: "/includes/findartist.php",
minLength:1,
select: function( event, ui ) {
$("#name").val(ui.item.label);
$("#form").submit();
}
});
});

Jquery ui autocomplete php retrieve names

I'm trying to use the jquery UI autocomplete widget to retrieve names out of a mysql table in a php file (nameSearch.php)
It's not retrieving the results properly. Is there anything wrong with the Jquery I have here? Should it return results to the input with id 'tags'?
I'm getting the '$_GET['term']' variable in the php file which I understand is sent from the autocomplete request to the php file?
This is the Jquery code I have:
<script>
$("#tags").autocomplete({
source: "nameSearch.php",
minLength: 2
});
</script>
php
<?php
$namePart=$_GET['term'];
$names = array();
// Create connection
$con=mysqli_connect('localhost','root','admin','filmdatabase');
// Query Database
$result = mysqli_query($con,"SELECT name FROM actor WHERE name like '%".$namePart."%'");
$arr = '';
while($row = mysqli_fetch_array($result)){
array_push($names,$row['name']);
}
echo json_encode($names);
?>
Thanks for your help
Adding $(document).ready(function(){....});? as a wrapper solved the Problem

PHP To Javascript Array?

I have googled and looked at SO for a while now and can't seem to figure this out. The only requirement Im trying to meet is to return a properly formatted javascript array that contains the results of the sql statement.
I.E.
Given a query:
SELECT NUMBERS FROM TABLE
And results:
NUMBERS
1
2
3
I would like to eventually get back an array like so
["1","2","3"]
Please help me understand where I am going wrong
Here is my php code
<?php
$mysqli = new mysqli("local.host.com", "user", "pass", "db");
$sql = "SELECT DISTINCT NAME FROM table";
$result = $mysqli->query($sql);
while($row = $result->fetch_array())
{
$rows[] = $row['NAME'];
}
echo(json_encode($rows));
$result->close();
/* close connection */
$mysqli->close();
?>
Here is my javascript:
function GetCards()
{
var cardarray = new Array();
//alert('test');
$.getJSON('getcardlist.php', function(data)
{
for(var i=0;i<data.length;i++)
{
cardarray.push(data[i]);
}
//return cardarray;
});
return cardarray;
}
EDIT:
Little more information, Im trying to setup an autocomplete list for jquery ui, this is my setup for the autocomplete widget.
var list = GetCards();
$( "#name" ).autocomplete({
source: list,
minLength: 2
And this is the error Im getting from chrome console
Uncaught TypeError: Cannot read property 'label' of null
GetCards is returning an empty array -- which is what you're passing on to the Autocomplete widget -- and causing the widget to throw up the TypeError exception. To pass on the populated array, move the code that instantiates Autocomplete into your getJSON success callback (I'm not sure you even need to loop through data -- unless you need to actually transform its contents in some way):
$.getJSON( 'getcardlist.php', function( data ) {
$( "#name" ).autocomplete( {
source: data,
minLength: 2
} );
} );
Alternatively, consider using Autocomplete's shorthand for loading directly from the data feed (see passing source as a string). However, this approach may require some additional work on the server-side to filter down the list as the user types -- if you want that behavior.
you have to use $.each to get the data
$.getJSON('getcardlist.php', function(data)
{
$.each(data, function(key, val) {
cardarray.push(val);
});
//return cardarray;
});

Jquery autocomplete not working with large array

I've got an array with 6000 plus user names that I've pulled from MySQL like this:
$pop = mysql_query("SELECT * FROM import_student");
while ($r = mysql_fetch_assoc($pop)) {
$student_array[] = $r['studentfirstname']." ".$r['studentlastname'];
}
$big_array = json_encode($student_array);
I then pass this array to JS and initialize my auto complete function like this.
<script>
$(document).ready(function() {
var availableTags = <?php echo $big_array; ?>;
console.log(availableTags);
$( "#tags" ).autocomplete({
source: availableTags
});
});
</script>
This works great when I limit the SQL results to 0,10, but when I don't limit and I get the 6000 or so usernames into the array, the autocomplete doesn't work. I get this error in firebug:
value is null
return matcher.test( value.label || value.value || value );
Anyone know what I'm doing wrong here? Like I said, this works when I limit the results. Something about having a large array? IDK.
I tested before (some 2k items for 1-2 letters) and it has to do with the parsing as well as rendering your large result set to the DOM.
You should reduce results by limiting the possibilities. You can do this by raising your minimum characters to at least 3-4.
Also, you should do a little caching on your result set instead of having jQuery re-parse it every entry. For example, I searched for ad. I should store in an object the results under the key ad.
var cache = {
'ad' : [...results...],
'adder' : [...results...],
...and so on...
}
When the autocomplete queries for ad again, it should search for the key in the cache first and return the results if it exists. You should have a caching logic to avoid stale data. Afaik, jQuery has simple caching demo in autocomplete.
i retrieve your same problem... you could use autocomplete using instead all array, a part creted by another script.. something like:
$('#tags').autocomplete({
source : "aScript.php",
};
and aScript.php:
$autocompleteValue = $_GET["term"];
$pop = mysql_query("SELECT * FROM import_student WHERE 'studentfirstname' LIKE '$autocompleteValue%'");
while ($r = mysql_fetch_assoc($pop)) {
$student_array[] = $r['studentfirstname']." ".$r['studentlastname'];
}
return json_encode($student_array);

jQuery Autocomplete Mysql PHP

Hi could some one please take a look at this and let me know where I'm going wrong. I am trying to get jQuery UI autocomplete to work. this is my code:
This is search.php
include "db_connect.php";
$search = $_GET['term'];
$result = mysql_query("SELECT Title FROM `movie` WHERE `Title` LIKE '%$search%' ORDER BY Title ASC") or die('Something went wrong');
$rows = array();
while ($row = mysql_fetch_assoc($result)){
$rows[] = $row;
}
print json_encode($rows);
?>
this is my javascript inline script
<script type="text/javascript">
$(document).ready(function()
{
$('#auto').autocomplete(
{
source: "./search.php",
minLength: 3
});
});
</script>
and this is the 'auto' div
<div id="searchTxtFieldDiv">
<p><input type="text" id="auto" /></p>
</div>
When I look at the call using firebug I see that search.php is returning
[{"Title":"Sin City"}]
jQuery is just displaying UNDEFINED
any ideas??
Have a look at jquery ui autocomplete documentation. The JSON you are returning does not match what the autocomplete is looking for. The object you return must have properties named label or value (or both).
You can try the following options:
Option 1: Change returned JSON
Change the JSON being returned to include the label/value properties such as:
[{"label":"Sin City"}]
From the examples it also seems to use the id property. I believe the above is the minimum requirement for the autocomplete to display a list of values. I think you can also return an array of strings and it will render it in exactly the same way as the above.
[ "Sin City", "Etc" ]
Option 2 : Change private _render function
Change the private _renderItem function for the autocomplete to use your custom properties as shown in this autocomplete example (untested):
$( "#project" ).autocomplete({
source: "./search.php",
minLength: 3
})
.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( item.Title )
.appendTo( ul );
};
This is a bit more flexible but much uglier imho.
#Shaun
Thanks mate, sometimes you just need someone to point out the obvious.
The way I finally got it to work was
include "db_connect.php";
$search = protect($_GET['term']);
$result = mysql_query("SELECT Title FROM `movie` WHERE `Title` LIKE '%$search%' ORDER BY Title ASC") or die('Something went wrong');
$json = '[';
$first = true;
while ($row = mysql_fetch_assoc($result))
{
if (!$first) { $json .= ','; } else { $first = false; }
$json .= '{"value":"'.$row['Title'].'"}';
}
$json .= ']';
echo $json;
atleast run mysql_real_escape_string() on $search before jamming it into a SQL Query.
The source: bit in your javascript is probably messing it up. You should remove the . if 'search.php' is at the 'top' of the documentroot directory.
Firebug will probably help you take a peak at the communication as well.
I was going to say this, always sanitize user inputs.
It's hard to say since I never used jQuery autocomplete but I think you should target the value of "#auto". Something like this: $('#auto').val().autocomplet

Categories