Autocomplete in the text box in PHP, Ajax and MySQL - php

Using Autocomplete text box to retrieve the data from the MySQL database table. my Ajax coding is working to retrieve the small amount of data. In my database table, I have more 300,000 records. The coding is not working when I used large data.
Please give suggestion about to retrieve a large data.
Which method is best to retrieve the data.
See my coding. It works fine to retrieve a small amount of data
<input type="text" name="protein_name" id="protein_name">
$("#protein_name").keypress(function (e){
var protein_name = $("#protein_name").val();
if(protein_name != "") {
$.ajax({
url: '<?php echo base_url(); ?>/index.php/Protein_Main/protien_search',
data: {protein_name: protein_name},
dataType: "json",
type: "POST",
success: function (res) {
$("#protein_name").autocomplete({
source: res
});
}
});
} });
PHP Coding
$query = $this->db->query("SELECT `Name_of_the_Protein` FROM `protein` WHERE Name_of_the_Protein Like '".$protein_name."%'");
$protein = $query->result();
echo json_encode($protein);

Autocomplete requires a few things.
An input element
<input type="text" id="nmRecipientSearch">
A couple of local javascript arrays:
(One containing a list of potential selections, and another with numeric unique ids corresponding to each selection)
var aryRecipientsFull=["Aaron","Adon","Andrew"];
var aryLrId=["1","2","3"];
A javascript .autocomplete handler bound to the input element:
$( "#nm_recipient_search" ).autocomplete({ source: aryRecipientsFull,
select: function( event, ui )
{
var numPosition,numLrId = 0;
//Find the index position within the array for the selected item (e.g. Adon)
numPosition=aryRecipientsFull.indexOf(ui.item.label);
//Set a variable to the numeric value corresponding to the selected item (e.g. 2)
numLrId=aryLrId[numPosition];
//Populate a hidden input field (nm_lr_id) to the numeric value
$('#nm_lr_id').val(numLrId);
//Set the focus to the next field once a selection has been made
$('#nm_text').focus();
}
});
A CSS style to ensure the autocomplete results appear above everything else:
ul.ui-autocomplete
{
z-index: 1100;
}
A couple of things to consider:
I'd recommend starting off using static arrays just to ensure that the UI looks okay
If you need to (re)populate the arrays dynamically then you may need to bind a .keyup event to the search field, perform an AJAX call to a PHP page which then does a query as you've suggested, but make sure that you limit the number of resulting records (perhaps 10 or 20 records).
Simply add "LIMIT 20" to the end of your SELECT query to achieve this.
I hope that helps.

Related

PHP - PDO - JQuery dynamic select element only allows the first option to be selected

For certain reasons (towards a larger picture), I have a select element that is populated by a php page. The data is populated properly within the element. However, when I make a selection the element always forces the first item in the list. If I "append" the returned data, I can select different items but if clicked again it will just keep appending on top of the existing items. If I "empty" before the "append" it shows the correct list but still forces the first item in the list and this happens whether I use onclick or onchange. Whatever code works will also need to be applied the same to this element being dynamically created on the same page later. As I understand it the $(document).on('click'... as opposed to $(document).click(... works better for dynamic elements. Any help is appreciated. Thanks, I am still new to this exchange and I hope I described my problem correctly. I have searched for hours about this problem, but I mostly get results about multiple select elements or populating a second select, and even potential answers I have tried do not work.
My data is pulled from _get_staffnames.php, and lets say it shows Frank, George, Todd.
$stmt = $myPDO->prepare( "SELECT userID, CONCAT(firstname,' ', lastname) AS Fullname FROM tbl_user ORDER BY Fullname ASC" );
$stmt->execute();
$results = $stmt->fetchAll();
foreach ($results as $row):
echo '<option value="' . $row['userID'] . '">' . $row['Fullname'] . '</option>';
endforeach
My HTML is:
<select name="userID1" id="userID1" class="namesClass" required>
<option selected value="">Select Staff</option>
</select>
One JQuery way I tried, specifically for the one element id "userID1", populates Frank, George, Todd...but when I pull down and click Todd, it still shows Frank (first in list) after the click.
$("#userID1").click(function() {
$("#userID1").load("_get_staffnames.php");
});
More towards the dynamic way I am going. This code allows me to choose Frank, George, or Todd and keeps the selection, but if I click on that given dynamic element again, the list keeps repeating the group +1 every time I click on it.
$(document).on('click', '.namesClass', function(e) {
var select_id = $(this).attr("name");
$.ajax({
type: "POST",
url: '_get_staffnames.php',
})
.done(function (returndata) {
$('#' + select_id).append(returndata);
})
});
When I try the .empty parameter before append as below, I get the correctly populated list (without multiple appended groups) but when I choose any item it always defaults to the first item in the list (Frank) again.
$(document).on('click', '.namesClass', function(e) {
var select_id = $(this).attr("name");
$.ajax({
type: "POST",
url: '_get_staffnames.php',
})
.done(function (returndata) {
$('#' + select_id).empty().append(returndata);
})
});
Is clicking on the Select element the only way you can load data from a remote source?
It's totally unconventional and by doing so, you are triggering the onclick event and performing the ajax method every time you click on any item of it which will eventually recreate its child elements on every callback and thus the first item being selected as default.
As kolunar pointed out, even when I clicked on my selection I was running ajax again. So, I just check if there is anything in the element before running ajax and it works. Feels silly now, but thanks for the time and input.
$(document).on('click', '.namesClass', function(e) {
var select_id = $(this).attr("name");
if ( $('#' + select_id).val() == '' ) {
$.ajax({
type: "POST",
url: '_get_staffnames.php',
})
.done(function (returndata) {
$('#' + select_id).empty().append(returndata);
})
}
});

How to build a dynamic query based on dropdown option?

EDITED:
SQL
$valuefromjs = $_REQUEST['var'];
$result6 = "SELECT DISTINCT $valuefromjs FROM persons ORDER BY $valuefromjs ASC";
$result7 = mysql_query($result6);
$num = mysql_num_rows($result7);
$dataRanges[0] = array('dataRanges');
for ($i=1; $i<($num+1); $i++)
{
$dataRanges[$i] = array( (int) mysql_result($result7, $i-1) );
}
echo json_encode($dataRanges);
HTML
<select id="combo2" class="combo" data-index="2"></select>
jQuery
$('#1combo').on('change', function () {
var jsonVar = $.ajax({
url : "visits/comboquery.php?var="+$(this).val(),
dataType: "json",
async: false,
success: function(response) {
}
}).responseText;
for (var i=1; i<objVar.length;i++)
{
$('#combo2').html("<option value="+objVar[i]+">"+objVar[i]+"</option>");
}
});
QUESTION:
I have an array with query results. Now i need that results be the combo2 options, what is wrong?
To my understanding the choice from combo1 will define which query to run for building combo2.
The issue: your PHP for building the combo2 is parsed at the server side i.e. the PHP code is always finished executing by the time the page reaches the user's browser and your javascript begins to execute.
If you have a finite set of possible queries that can generate the seconds combo (which should be the case since combo1 has a finite number of options), you can create all of them, each with a different id, and maintain them hidden (css "display: none").
<select id="firstCombo2" class="combo2">
...
</select>
<select id="secondCombo2" class="combo2">
...
</select>
etc.
Now, when the user makes a selection from combo1, you can decide which one of the hidden combo2's you are going to display (css "display: block").
$('select#combo1).on("change", function(){
$('select.combo2').css('display','none'); //hide all combo2's
if($(this).val()=='Opt1'){
$('select#firstCombo2').css('display','block');
}else if($(this).val()=='Opt2'){
$('select#secondCombo2').css('display','block');
}
}
You should use AJAX in order to solve your problem.
on combo1 onChange call an AJAX call to your server and send selected value of combo1.
Then in your php code run query with value received from AJAX request and construct a new combo box with options in string and echo back that string. You can use that AJAX response to populate new combo2.

Is it possible to have drop down boxes in a tablesorter plugin?

I have a table that generates perfectly using php, ajax and the tablesorter plugin. I now would like to make a few of the input fields into dropdown boxes so the user can select an option if it needs to be changed. This all will then need to be saved to a database. Here is what I have so far:
$('#getInfo').live('click', function() {
//clear table before search
$("#inventoryUpdate tbody tr").remove();
$('#messageInv').html('Please be patient, this might take a minute');
$.ajax({
type: "POST",
async: true,
url: "getInventory.php",
dataType: "json",
data: ({skuStart: $("#startSkuRange").val(), skuEnd: $("#endSkuRange").val(), processDate: $("#processDate").val(),
source: $("#source").val()}),
success: function(data){
$('#messageInv').hide();
//console.log(data);
var myselectoptions = '';
if(data.isbn2 === null){
$("#inventoryUpdate").append('<tr><td>No Records Found</td></tr>');
}else{
for(var x=0;x<data.isbn2.length;x++)
{
$.each(data.defect2[x], function(index, val)
{
myselectoptions += '<option value="'+data.defect2[x][index].option+'">'+data.defect2[x][index].option+'</option>';
});
$("#inventoryUpdate").append('<tr><td id="tableSKU">'+data.sku[x]+'</td><td id="tableISBN">'+data.isbn2[x]+
'</td><td><input type="text" id="tableQuantity" value="'+data.quantity[x]+
'"/></td><td><select id="tableDefect">'+myselectoptions+
'"</select></td><td><input type="text" id="tableSource" value="'+data.source[x]+
'"/></td><td><input type="text" id="tableFeature" value="'+data.feature[x]+
'"/></td><td><input type="text" id="tableLocation" value="'+data.location[x]+
'"/></td><td><input type="text" id="tableProcessDate" value="'+data.processDate[x]+
'"/></td><td><input type="text" id="tableBookType" value="'+data.booktype[x]+
'"/></td><td><input type="text" id="tableCreatedBy" value="'+data.created[x]+
'"/></td><td><input type="text" id="tableModifiedBy" value="'+data.modified[x]+
'"/></td></tr>');
}
$("#inventoryUpdate").trigger("update");
} // end of else statement
} // end of success function
});// end of ajax call
}); // end of inventory update function
I would like to have the tableDefect and tableFeature inputs become drop down boxes that are populated dynamically, and default to the current info from the database. For example, if the defect from the database is "rip in dust jacket" that would be the option that is selected, but I also need the rest of the options (no defects, water damage etc.) from the database to be available if it needs to be changed. I would think that I need to change the input type to a select, but then how do I go about populating it? Would that require another call to the database for the information?
Is this even possible to do with this plug-in?
EDIT: I have pasted in the new code based on the answer below, I now am getting 19 "options" (it just says undefined not the actual value returned) for the first record, 38 for the second etc. There should only be 19 options.
If I am reading you correctly just replace <input type="text"......> with
<select id=...><option>...</option></select>
As far as populating the selects dynamically that can be handled a few different ways. With your ajax you would get the select values maybe by changing your existing
data.defect[x] into a multidimensional object so instead of it being just a string you would output an array that will get converted to JSON on your backend so your object would look like
defect[{"option":"value"},{"option":"value"},{"option":"value"},{"option":"value"}]
Where when your building your table in the succession part you would loop over that object. You would essentially do the same as you do now.. except. your select would look like
var myselectoptions = '';
$.each(data.defect[x], function(index, val)
{
myselectoptions += '<option value="'+data.source[x][index].option+'">'+data.source[x][index].option+'</option>';
});
'"/></td><td><select id="tableDefect">'+myselectoptions+'....
now this is pure concept, I haven't tested it, and its likely to need some tweaking to fit your needs specifically but this is the core concept of one of a few ways you can handle what you want done, that fits into what you are currently doing, without having to alter it too much.

How do I get the values and id's of multiple select lists and pass it to AJAX?

I am trying to iterate through a number of selects in a cell of a table (they are not in a form). I have a submit button when pressed is supposed to retrieve the values and id of each select list which I will pass to the server via AJAX and PHP. My table is a table of students of a course. The table contains the students name and their attendance for a lesson in the course.
This is my table on Pastebin and jsFiddle. http://pastebin.com/NvRAbC7m and http://jsfiddle.net/4UheA/
Please note that this table is entirely dynamic. The no. of rows and the info in them is dynamically driven.
This is what I'm trying to do right now with jQuery. Please excuse the logic or the complete nonsense that is my JavaScript skills. I don't actually know what I'm doing. I'm just doing trial and error.
$('#saveAttendances').live('click', function()
{
var attendSelect = $('.attendSelect');
var students = new Array();
//get select list values and id.
for(var i in attendSelect)
{
students['student_id'] += attendSelect[i].id;
students['student_id']['attedance'] += attendSelect[i].value;
console.log(students['student_id']);
}
//after retrieving values, post them through ajax
// and update the attendances of students in PHP
$.post("",{ data: array }, function(msg)
{
alert(msg);
});
});
How do I get the values and id's of each select list and pass it to AJAX?
Edit
If you insist on going against jQuery's grain and using invalid HTML, here's a suitable solution for you:
$(function() {
$('button').click(function(){
var data = $(".attendSelect").wrap('<form/>').serialize();
$.post('process.php', data, function(response){ ... });
return false;
});
});​
Worth mentioning, this example does not rely on fanciful .on() or .live() calls. However, this requires you to have the proper name attribute set on your <select> elements as described below. This also resolves your invalid numeric id attributes issue.
See it working here on jsFiddle
Original Answer
First off, some minor changes to your HTML. You need to wrap your <select> elements in a <form> tag. Using the form tag will give you access to jQuery's .serialize() method which is the exact functionality you're looking for. Personally, I'd recommend doing things the jQuery Way™ instead of implementing your own form a serialization. Why reinvent the wheel?
Next, your td have non-unique IDs. Let's update those to use a class attribute instead of an id. E.g.,
<td class="studentName">Aaron Colman</td>
Secondly, your <select> elements could benefit from a name attribute to make form processing way easier.
<select class="attendSelect" name="students[241]">
...
<select class="attendSelect" name="students[270]">
...
<select class="attendSelect" name="students[317]">
...
Lastly, jQuery's .serialize() is going to be your winning ticket.
​$(function() {
$('form').submit(function(){
$.post('process.php', $(this).serialize(), function(response){ ... });
return false;
});
});​
Upon submit, the serialized string will look something like
students[241]=Late&students[270]=Absent&students[317]=default
See it working here on jsFiddle
live() is deprecated as of jQuery 1.7, use on() instead
http://api.jquery.com/on/
students is an array, so I don't think you can do students['student_id'], if you would like to push an array of student, you can:
$('#saveAttendances').on('click', function() {
var students = [];
// iterate through <select>'s and grab key => values
$('.attendSelect').function() {
students.push({'id':$(this).attr('id'), 'val':$(this).val()});
});
$.post('/url.php', {data: students}, function() { // do stuff });
});
in your php:
var_dump($_POST); // see what's inside :)
As #nathan mentioned in comment, avoid using number as the first character of an ID, you can use 'student_<?php echo $id ?>' instead and in your .each() loop:
students.push({'id':$(this).attr('id').replace('student_', ''), 'val':$(this).val()});
Here's jQuery that will build an object you can pass to your script:
$('button').click(function() {
var attendance = new Object;
$('select').each(function() {
attendance[$(this).attr('id')] = $(':selected', this).text();
})
});​
jsFiddle example.
This results in: {241:"Late",270:"Absent",317:"Late"}
Edit: Updated to iterate over select instead of tr.
Perhaps you want something like below,
DEMO
var $attendSelect = $('#tutorTable tbody tr select');
var students = {};
$attendSelect.each (function () { //each row corresponds to a student
students[$(this).attr('id')] = $(this).val();
});
This would give you an object like below,
students = { '241': 'Late', '270': 'Absent', '317': 'default' };
If the above is not the desired structure then modify the .each function in the code.
For ex: For a structure like below,
students = [{ '241': 'Late'}, {'270': 'Absent'}, {'317': 'default'}];
You need to change the code a little,
var students = [];
...
...
students.push({$dd.attr('id'): $dd.val()});
var $select = $('.attendSelect'),
students = [];
$('body').on('click', '#saveAttendances', function() {
$select.each(function(k, v) {
students[k] = {
student_id : $(this).attr('id'),
attedance : $(this).val()
};
});
console.log(students);
});

Autocomplete: populate multiple fields based on selection

I have a form, and there are 5 fields. The first field is an autocomplete field. I'd like to have the other 4 fields populated based on the autocomplete field selection. The docs in github ajax.autocompleter page reference setting an id and using a js function to call the id value, but this doesn't seem efficient if using multiple fields/need multiple values in addition to the ac value.
I'm using scriptaculous, and php. I have the autocompleter functioning, but am not sure on the rest of it. I'm also not clear on how to set the additional field parameters on the php end. I suppose that I could set the id="field1Val='blah'&field2Val='blah2'" then use js to parse and populate fields, but something about that just doesn't feel right.
Any idears?
this is what we use: a jquery plugin. The good thing about this one is that you can add a callback function that allow you to change the "current" behavior.
about the line 385 you have function that parses the result:
function parse(data) {
var parsed = [];
var rows = data.split("\n");
for (var i=0; i < rows.length; i++) {
var row = $.trim(rows[i]);
if (row) {
row = row.split("|");
parsed[parsed.length] = {
data: row,
value: row[0],
result: options.formatResult && options.formatResult(row, row[0]) || row[0]
};
}
}
return parsed;
};
you can create your own function that depending on what you get (you can send a json from the server) and then execute javascript and drive the form controls.
hope help you

Categories