Jquery autocomplete not working with large array - php

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

Related

Loading mysql rows from PHP into autocomplete jquery

<?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.

Iterate through php array in jquery

So I have a php array that I am JSON encoding and handing to some JQuery. Basically I am using the information from the array to dynamically change the content of one drop down based on the value of another drop down. I am running into some problems with the JQuery though as JQuery is pretty new to me.
First off my PHP:
<?php
$sql = mysql_query("SELECT * FROM menu") or die(mysql_error());
$menuItems = array();
$x = 0;
while($row = mysql_fetch_object($sql))
{
$menuItems[$x]['ID'] = $row->ID;
$menuItems[$x]['parent'] = $row->parent;
$menuItems[$x]['name'] = $row->Name;
$menuItems[$x]['header'] = $row->header;
$menuItems[$x]['Sort'] = $row->sort;
$x++;
}
?>
This code returns an array of ~30 menu items.
Then my JQuery:
<script>
var menuItems = <?php echo json_encode($menuItems); ?>;
$('#dropdown1').change(function (){
if($('#dropdown1').val() == 0){
$('dropdown2').children().remove().end()
for(var x = 0; x < menuItems.length; x++){
if(menuItems[x]['header'] == 1){
$('#dropdown2').options[menuItems[x]['sort']] = new Option(menuItems[x]['name'], menuItems[x]['sort']);
}
}
}
});
</script>
What I want this to do is when dropdown1 is changed, dropdown2's options are removed and then repopulated with specific things from the array.
Currently this code does delete the options for dropdown2 when dropdown1 is changed but re-population just isn't working. From what I can tell in testing, the for loop to iterate through the array is only entered once, despite their being about 30 items in it and I assume that is were my main problem is.
What am I doing wrong here?
change it to
for(var x = 0; x < menuItems.length; x++){
if(menuItems[x]['header'] == 1){
var option = $('<option />', {
text : menuItems[x]['name'],
value: menuItems[x]['sort']
});
$('#dropdown2 option[value="'+[menuItems[x]['sort']]+'"]').replaceWith(option);
}
}
$('#dropdown2').options[] is not valid, as jQuery doesn't have those methods, that's for plain JS DOM nodes.
So from the comments there seemed to be some confusion on what I meant, and I apologize. It was one of the instances where the explanation made sense to me, but I just must not have conveyed everything well enough.
To clear up a little bit of the confusion. The array that was passed from the PHP code to the javascript contained everything I could ever need for the second drop-down.
As many pointed out the .options[] was the culprit for why the code wasn't executing. This was simply from another example I had found, and with my limited knowledge I assumed it was correct, and it wasn't.
I instead used the the .append() function and things seem to be working normally now.

Javascript countdown not working for php loop

Hello i me and a friend have a maffia game. I have a countdown timer code but it only works when i use one timer. But i need to use it in a loop to get more timers in a table. I searched on google but nothing really helped. I saw that i had to use different id's but that didn't work for me. I have little knowledge of javascript.
This are my codes:
While loop:
while($info = mysql_fetch_object($dbres))
{
$j = 0;
$bieding = mysql_fetch_object(mysql_query("SELECT `bedrag` FROM `biedingen` WHERE `veilingid`='{$info->id}' ORDER BY `bedrag` DESC LIMIT 1"));
$tijd = ($info->tijd + $info->duur * 60 * 60 - $time);
echo '<tr>
<td>'.veilingnaam($info->id,1,1).'</td>
<td>'.usernaam($info->veiler,1,1).'</td>
<td>€'.getal($bieding->bedrag).'</td>
<td><div id="teller'.$j.'"></div></td>
</tr>';
}
Javascript part:
<script type="text/javascript">
var seconds = <?= ($tijd+1) ?>;
var countdown = document.all? document.all["teller<?= $j?>"] : document.getElementById? document.getElementById("teller<?= $j?>") : "";
var woord = "seconden";
function display()
{
seconds=seconds-1;
if(seconds==1){ woord="seconde"; }
if(seconds==0){ woord="seconden"; }
if(seconds<0)
{
self.location.replace(self.location);
}
else
{
if (countdown)
{
countdown.innerHTML=seconds+" "+woord;
setTimeout('display()',1000);
}
}
}
display();
</script>
Your while loop goes through table rows in a DB, but your JavaScript code is not part of that loop. That means you generate a HTML table for each row, but then you create <script>...</script> which includes $tijd/$j only for the last row (assuming that your while executes before the script is added to the page.
Possible workarounds:
Add a jQuery's selector, something like $("div.teller").each(function(){...}); and in that function create a timer and/or any other JavaScript code you need associated with that div.Note that this requires your div to get a CSS class "teller".
Create all JavaScript code that is needed for each DB's table row inside the PHP's while loop, but this would probably get really messy.
Also, I advise you to take a look at JavaScript's setInterval(), since it is more appropriate than setTimeout() for what you want to do.
Another thing to consider: all your timers would have a one second tick. It seems to me that it is better to have a single timer and just keep numbers of seconds (whatever that might be) in a JavaScript array (this one is easily created in PHP's while loop).
Edit: Here is one way to do this:
$data = array();
while($info = mysql_fetch_object($dbres))
{
... /* your current code */
$data[] = "{ id: 'teller$j', seconds: $tijd }";
}
$data = "[ ".implode(", ", $data)." ]";
Now, create your JavaScript code outside of the loop:
<script type="text/javascript">
var data = <?php echo $data; ?>; // It is not advisable to use <?= ... ?>
// Get references to divs via saved ids (seconds are already saved
for (i = 0; i < data.length; i++)
data.div = document.getElementById(data.id); // No need for document.all; IE supports getElementById since version 5.5
...
</script>
Now, adapt display() to work with the elements of your data array.

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

Parse data from php to jsquery.flot.pie

I've seen some questions about this already but I still couldn't clear the fog around this...
I have this sql statement to get data:
<script type="text/javascript">
<?php
$query = "SELECT rel_id, SUM(suma) FROM $tbl_rel_balansas INNER JOIN $tbl_balansas ON $tbl_rel_balansas.rel_id = $tbl_balansas.id WHERE $tbl_rel_balansas.member_id = '$_SESSION[id]'";
$result = mysql_query ($query);
while($row = mysql_fetch_array($result)){
echo 'var some_data = ' . json_encode( $viso );
}
?>
Next is the js part:
$(function () {
$.plot($("#placeholder"), [some_data],
{
series: {
pie: {
show: true
}
},
legend: {
show: false
}
});
});
</script>
I was thinking I could reach the data in some_data and use it to display it in the pie chart, unfortunately this is not the way to go.
Any help and suggestions are greatly appriciated ! :)
The most likely problem is that your numeric data is being interpreted as a string.
From the API.txt:
Note that to simplify the internal
logic in Flot both the x and y values
must be numbers (even if specifying
time series, see below for how to do
this). This is a common problem
because you might retrieve data from
the database and serialize them
directly to JSON without noticing the
wrong type. If you're getting
mysterious errors, double check that
you're inputting numbers and not
strings.
So either force your data to numeric types on the PHP side, or do it in javascript, perhaps with .Number(some_data)

Categories