I found a couple of similar questions but nothing with the same "variables" so here we go:
I have a simple form where I enter a name and I need the rest of the form to be completed automatically (ID).
Fetching the data in the DB is not an issue, I'm able to return Json using PHP (Search.php):
//get search term
$searchTerm = $_GET['term'];
//get matched data from table
$query = $db->query("SELECT * FROM info_employer WHERE Prenom LIKE '%".$searchTerm."%' ORDER BY Prenom ASC");
while ($row = $query->fetch_assoc()) {
$data[] = array( Nom => $row['Prenom'] . ' ' . $row['Nom'], Num => $row['Num'] );
}
//return json data
echo json_encode($data);
This give me an array that look like this:
[{"Nom":"Andre Nadeau","Num":"104J"},{"Nom":"Andre Potvin","Num":"130J"},{"Nom":"Andre Thibodeau","Num":"91J"}]
Friends told me that I should use Jquery and Ajax to use this array to fill my form but I have 2 issue.
First If I return an Array instead of "just the name" my autocomplete form don't work anymore. It give me X numbers of blank space (depending the number of results).
And of course my biggest problem is that i'm not able to send the ID (Num) in the form
Javascript i'm using to autocomplete the name :
<script>
$(function() {
$( "#Nom" ).autocomplete({
source: 'Search.php',
})
})
</script>
You need to change the return object to make it match the spec here
$data[] = array( "label" => $row['Prenom'] . ' ' . $row['Nom'], "value" => $row['Num'] );
This should result in an array of objects with a 'label' and 'value' key. This will work with your autocomplete.
Related
I have a leaderboard where if you click on a name a popup is displayed : https://jsfiddle.net/pvwvdgLn/1/
In practice, I will pull the list of the leaderboard from a DB.What you see here in the list are static names of employees,just for reference. So,how do I assign names using data attributes and search for that name in the JSON?
There are various fields in the popup like: Name,Email,Date of birth etc which I want to display for the respective person whose name is clicked by the user.
I have below JSON which is fetching me the array which contains all these data of all the people in the list :
<?php
session_start();
$servername = "xxxxx";
$connectioninfo = array(
'Database' => 'xxxxxxxxxxxxx'
);
$conn = sqlsrv_connect($servername, $connectioninfo);
if (!$conn) {
echo 'connection failure';
die(print_r(sqlsrv_errors() , TRUE));
}
$q1 = "select top 10 *
from pointsBadgeTable
WHERE WeekNumber ='week51'
order by pointsRewarded desc";
$stmt = sqlsrv_query($conn, $q1);
if ($stmt == false) {
echo 'error to retrieve info !! <br/>';
die(print_r(sqlsrv_errors() , TRUE));
}
do {
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$result[] = $row;
}
}
while (sqlsrv_next_result($stmt));
sqlsrv_free_stmt($stmt);
sqlsrv_close($conn); //Close the connnectiokn first
//Set content type to json
header('Content-Type: application/json');
//Echo a json object to the browser
echo json_encode($result);
?>
As can be seen in the query,it fetches JSON for all the top10 ,whose names can be seen in the list.
the html and JS related to the popup is here : https://jsfiddle.net/woef5mn6/
How can I display the respective data in the popup from the JSON only for the person whose name is clicked ?
please help me.
I have edited your fiddle to show how your problem can be solved. This is just a simple solution. It needs to modified according to your requirement.
Here is the fiddle
I am creating the employee list from your JSON and populating the ordered list
function employeeList() {
$("#myOL").empty();
$.each(employee, function(i,o) {
$("#myOL").append("<li><mark>" + o.EmployeeName + "</mark><small>" + o.score + "</small></li>");
});
}
Then onclick of the individual employee, i am getting his details from JSON by his name and then populating the popup details (as a best practice here - you should get the employee details by calling a service through ajax using a unique identifier [employeeId] ):
function getEmployeeByName(name) {
var index = -1;
var filteredObj = employee.find(function(item, i) {
if(item.EmployeeName === name){
index = i;
}
});
return employee[index];
}
Hope this helps!
How would I bind or use the so called "autocomplete" feature on to the code below in order to use the autocomplete features keyboard up, down and enter functionality, because currently my code doesn't have that. It is on wordpress template and it is just being controlled by mouse for right now.
<script>
$(document).ready(function(){
$("#search-box").keyup(function(){
$.ajax({
type: "POST",
url: "autocomplete.php",
data:'keyword='+$(this).val(),
success: function(data){
$("#suggesstion-box ").show();
$("#suggesstion-box").html(data);
}
});
});
});
function selectCountry(val) {
$("#search-id").val(val);
$("#suggesstion-box").hide();
}
function updateSearchBox(el) {
$("#search-box").val($(el).html());
}
</script>
I have tried using
$("#search-box").keyup.autocomplete(function() {
or
$("#search-box").autocomplete(function() {
or even
$("#search-box").autocomplete.keyup(function() {
But it doesn't pull the list. I know there is something wrong with my AJAX causing me to have this issue of keyboard is not working correctly. Any Suggestions?
Ok... I have changed my php to give out a json.
Autocomplete.php
<?php
include_once "functions.php";
if(isset($_POST['keyword']))
{
$database = lookup_connectToDatabase();
$result = pg_query($database, "SELECT country, id, state FROM customers WHERE country iLIKE '" . $_POST["keyword"] . "%' OR id iLIKE '" . $_POST["keyword"] . "%' ORDER BY country");
if (!$result){
echo "<div class='show' align='left'>No matching records.</div>";
}else {
while($row=pg_fetch_assoc($result)){
$array[] = array(
'label' = $row['id'].': '.$row['country'].', '.$row['state'],
'value' = $row['id'],
);
}
echo json_encode ($array);
}
}
?>
But still doesn't seem to work right. What am I missing with this json?
I suspect you're looking for: http://jqueryui.com/autocomplete/#remote
In your script, this might look like:
$(document).ready(function(){
$("#search-box").autocomplete({
minLength: 0,
source: "autocomplete.php",
select: function(e, ui){
$("#search-box").val(ui.item.label);
$("#search-id").val(ui.item.value);
return false;
}
});
});
See More: http://api.jqueryui.com/autocomplete/#option-source
String: When a string is used, the Autocomplete plugin expects that string to point to a URL resource that will return JSON data. It can be on the same host or on a different one (must provide JSONP). The Autocomplete plugin does not filter the results, instead a query string is added with a term field, which the server-side script should use for filtering the results. For example, if the source option is set to "http://example.com" and the user types foo, a GET request would be made to http://example.com?term=foo. The data itself can be in the same format as the local data described above.
If you must use POST, this can be done, but it's a bit more complex.
Function: The third variation, a callback, provides the most flexibility and can be used to connect any data source to Autocomplete.
This might look like:
$(document).ready(function(){
$("#search-box").autocomplete({
minLength: 0,
source: function(req, resp){
$.ajax({
type: "POST",
url: "autocomplete.php",
data:'keyword=' + req.term,
success: function(d){
resp(d);
}
});
},
select: function(e, ui){
$("#search-box").val(ui.item.label);
$("#search-id").val(ui.item.value);
return false;
}
});
});
These examples are untested since you did not provide example data.
Update
Based on your autocomplete.php file, I would suggest the following:
<?php
include_once "functions.php";
if(isset($_POST['keyword'])){
$database = lookup_connectToDatabase();
$result = pg_query($database, "SELECT country, id, state FROM customers WHERE country iLIKE '" . $_POST["keyword"] . "%' OR id iLIKE '" . $_POST["keyword"] . "%' ORDER BY country");
$data = array();
if ($result){
while($row=pg_fetch_assoc($result)){
$data[] = array(
"label" => $row['country'].', '.$row['state'],
"value" => $row['id'],
);
}
}
header('Content-Type: application/json');
echo json_encode ($array);
}
?>
This should return an Array of objects with label and value properties.
The label property is displayed in the suggestion menu. The value will be inserted into the input element when a user selects an item. If just one property is specified, it will be used for both, e.g., if you provide only value properties, the value will also be used as the label.
If there are no matches, we'll just get an empty array in return. So let's say we get the following response:
[
{
"label": "United States, California",
"value": 420
},
{
"label": "United States, New York",
"value": 100
}
]
When one of these is selected, the select callback is executed and #search-box will receive the ui.item.label; #search-id will receive the ui.item.value.
Is it possible to update the server-side JSON file using AJAX in bootstrap-table?
data-url="scripts/users.php"
I am using a PHP file to echo the output of the sql queries to the table.
First Name | Last Name | Category | Group
This works well, but I want to add 4 select tags each to filter a column. I have replicated the server-side JSON within users.php but this time it will echo the filtered rows to the JSON.
Can this be done? How can I switch to the filtered JSON?
NOTE: all this logic is within users.php (aside from the AJAX of course).
if (!empty($_POST['first_name'])) {
//code to create and return filtered JSON
} else if (!empty($_POST['last_name'])) {
//code to create and return filtered JSON
} else if (!empty($_POST['category'])) {
//code to create and return filtered JSON
} else if (!empty($_POST['group'])) {
//code to create and return filtered JSON
} else {
//code to create and return unfiltered JSON
/*THIS ALWAYS EXECUTES ONLOAD, BUT **I WANT IT TO GIVE WAY FOR THE FILTERED JSON AND ONLY REACTIVATE ONLOAD OR IF ALL FILTERS ARE REMOVED***/
}
UPDATE:
In my users.php code I have successfully been able to run each filtered query individually (depending on what is selected). When the page first loads the table is empty but present. Users must select at least one option for the table to output any data.
I am having issues letting the table (written in the .html page) know to switch to the filtered results while the filter is active.
Here is the code that resides in each of the if/else conditions:
$limit = $_GET['limit'];
$offset = $_GET['offset'];
fname = $_POST['first_name'];
if (!empty($_POST['first_name'])) { //filter by the selected name
//get TOTAL rows for PAGINATION
$stmt_TOTAL_ROWS = "SELECT first_name, last_name, category, group
. "\
n "
. "
FROM users
.
"\n"
.
"WHERE first_name ='$fname'";
$result_TOTAL_ROWS = mysqli_query($mysqli, $stmt_TOTAL_ROWS);
$num_rows_TOTAL_ROWS = mysqli_num_rows($result_TOTAL_ROWS);
$stmt = "SELECT first_name, last_name, category, group
. "\
n "
. "
FROM users
.
"\n"
.
"WHERE first_name ='$fname' ORDER BY first_name LIMIT $offset, $limit";
$result = mysqli_query($mysqli, $stmt);
$cart = array();
$i = 0; //index the entries
if ($num_rows_TOTAL_ROWS > 0) { //if table is populated...
// enter data of each row
while ($row = mysqli_fetch_assoc($result)) {
$cart[$i] = array(
"First Name" => htmlspecialchars($row['first_name']),
"Last Name" => htmlspecialchars($row['last_name']),
"Category" => htmlspecialchars($row['category']),
"Group" => htmlspecialchars($row['group']),
);
$i = $i + 1; //add next row
}
//encoding the PHP array
$json_server_pagination_data = array(
"total" => intval($num_rows_TOTAL_ROWS), // total rows in data
"rows" => $cart, //data
);
echo json_encode($json_server_pagination_data); // allow table to access the data
} else {
//do nothing . no data in sql query
}
}
I'm in the process of establishing a website which uses JQuery's auto complete to give users suggestions on pages. I store the page ID and title in a SQL database (connecting using PDO). At the moment, I've got the auto complete feature working, however, I am absolutely stumped on how to get the auto complete list to turn into clickable links which direct the user to the relevant page based off the page ID in the database.
Here's my search.php file
<?php
require('includes/connect.class.php');
if (isset($_GET['term'])) {
$return_arr = array();
try {
$stmt = $conn->prepare('SELECT id, locationName FROM locations WHERE locationsName LIKE :term');
$stmt->execute(array(
'term' => '%' . $_GET['term'] . '%'
));
while ($row = $stmt->fetch()) {
$return_arr[] = $row['locationName'];
}
}
catch (PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
echo json_encode($return_arr);
}
?>
and my JavaScript
$(function() {
$(".locationlist").autocomplete({
source: "search.php",
minLength: 1
});
});
The database looks like this
Locations
|---ID---||---locationName---|
| 1 || Test1 |
| 2 || Test2 |
----------------------------
I've done some research, and I believe I need to modify JQuery to display an array of objects. I'm not too sure how to do this.
What would be the best way to have my auto complete list get the page ID from the SQL database and become clickable links?
You don't actually need for clickable links there. You can redirect the page within the autocomplete's select event , where you have access to the selected item object:
ui (Type: Object):
item (Type: Object):
An Object with label and value properties for the selected option.
ui.item.value will be the page ID generated with your PHP
$(".locationlist").autocomplete({
source : "search.php",
minLength: 1,
select : function(event, ui){
// You may need to change this part, as I don't know the exact values:
location.href = "http://your-site.com/" + ui.item.value;
}
});
As for your PHP, you can modify the output array like so:
while ($row = $stmt->fetch()) {
$return_arr[] = array(
'value' => $row['ID'],
'label' => $row['locationName']
);
}
I'm using jQuery autocomplete with PHP source file that connects to MySQL and get the info to show as autocomplete on input field. Here's my code:
Index/Input
<script>
$(function() {
$("#search").autocomplete({
source: 'http://localhost/testes/autocomplete.php',
minLength: 3
});
});
</script>
<input type="text" id="search"/>
autocomplete PHP
$req = "SELECT DISTINCT name FROM faculty WHERE name LIKE '%".$_REQUEST['term']."%'";
$query = mysql_query($req);
while($row = mysql_fetch_array($query)){
$results[] = array('label' => $row['name']);
}
echo json_encode($results);
The problem is, it returns good values and other null values. But, in the last case, the values should not be null because they are in the database.
For example, in the database I have the entries:
ISCTE - Instituto Universitário
INDEG-ISCTE Business School
Searching by 'iscte' the autocomplete gives second one but the first one appear as null.
Thank you for you time,
Regards,
Hugo
That is because the encoding. Use this:
...
while($row = mysql_fetch_array($query)){
$results[] = array('label' => utf8_encode($row['name']));
}
...
Your database should set to UTF8, but by the way, this fix it.