jQuery UI Autocomplete category is selecting only results in all categories - jquery-ui-autocomplete

I have used the jQuery UI Autocomplete demo source code for the Categories example (http://jqueryui.com/autocomplete/#categories) and have it working (querying a database which returns a JSON array).
I'm building a search function for an art gallery and my categories are Artists and Exhibitions. I want to show results from one or both categories. My problem is that results are only showing when the search term covers a result in both categories.
My suggestions script uses the search term to query two different database tables. I format and append the results into a single JSON array with rows for ["id"], ["value"], ["label"] and ["category"].
So for the search term CORN, the results that come back might be:
{ label: "Christopher Corner", category: "Artists" },
{ label: "New Pictures From Cornwall", category: "Exhibitions" },
{ label: "Cornie Collins", category: "Artists" },
At the moment when I type a search term, the possible results are only shown as long as a result is possible in ALL my categories, rather than what I want, which is one or more. So when I type CORN, I can see an Artist named Corner, and an Exhibition about Cornwall, but the minute I type the E of CORNE, all the options disappear, including the Artist whose name is Corner (which I would expect to remain).
I'm new to jQuery and jQuery UI and struggling to understand where the logic would be to select a list item from any category rather than all of them.
I have edited to add my code. This is the backend suggestions file - search_suggestions.php:
<?php
# if the 'term' variable is not sent with the request, exit
if (!isset($_REQUEST['term'])) {
exit;
}
# retrieve the search term that autocomplete sends
$term = trim(strip_tags($_GET['term']));
$a_json = array();
$a_json_row = array();
# connect to database, send relevant query and retrieve recordset
include 'includes/db_access.php';
$compoundFind = $fm->newCompoundFindCommand('web_Artists');
$request1 = $fm->newFindRequest('web_Artists');
$request2 = $fm->newFindRequest('web_Artists');
$request1->addFindCriterion('Last name', '*'.$term.'*');
$request2->addFindCriterion('First name', '*'.$term.'*');
$compoundFind->add(1, $request1);
$compoundFind->add(2, $request2);
$compoundFind->addSortRule('Last name', 1, FILEMAKER_SORT_ASCEND);
$result = $compoundFind->execute();
if (FileMaker::isError($result)) {
die();
}
$records = $result->getRecords();
# loop through records compiling JSON array
foreach ($records as $record) {
$artistID = htmlentities(stripslashes($record->getRecordID())) ;
$artistName = htmlentities(stripslashes($record->getField('Full name'))) ;
$a_json_row["id"] = $artistID;
$a_json_row["value"] = $artistName;
$a_json_row["label"] = $artistName;
$a_json_row["category"] = "Artists";
array_push($a_json, $a_json_row);
}
$findCommand = $fm->newFindCommand('web_Exhibitions');
$findCommand->addFindCriterion('Title', '*'.$term.'*');
$result = $findCommand->execute();
if (FileMaker::isError($result)) {
die();
}
$records = $result->getRecords();
foreach ($records as $record) {
$exhibitionID = htmlentities(stripslashes($record->getField('Exhibition ID'))) ;
$exhibitionTitle = htmlentities(stripslashes($record->getField('Title'))) ;
$a_json_row["id"] = $exhibitionID;
$a_json_row["value"] = $exhibitionTitle;
$a_json_row["label"] = $exhibitionTitle;
$a_json_row["category"] = "Exhibitions";
array_push($a_json, $a_json_row);
}
echo json_encode($a_json);
flush();
?>
And here is the JS in my section which sets things up:
<style>
.ui-autocomplete-category {
font-weight: bold;
padding: .2em .4em;
margin: .8em 0 .2em;
line-height: 1.5;
}
</style>
<script>
$.widget( "custom.catcomplete", $.ui.autocomplete, {
_create: function() {
this._super();
this.widget().menu( "option", "items", "> :not(.ui-autocomplete-category)" );
},
_renderMenu: function( ul, items ) {
var that = this,
currentCategory = "";
$.each( items, function( index, item) {
var li;
if ( item.category != currentCategory ) {
ul.append( "<li class='ui-autocomplete-category'>" + item.category + "</li>" );
currentCategory = item.category;
}
li = that._renderItemData( ul, item );
if ( item.category ) {
li.attr( "aria-label", item.category + " : " + item.label );
}
});
}
});
</script>
<script>
$(function() {
$( "#searchInput" ).catcomplete({
minLength: 2,
source:'search_suggestions.php'
});
});
</script>
Finally this is the actual input field on the page:
<input class="u-full-width" placeholder="Search" id="searchInput" />
Sorry if this is too much code!

Related

How to save multiple image path to database while image is saved to server

I have this code on how to save multiple images to server using codeigniter and ajax
I have gone through this code, though i'm still learning Ajax, Json and Javascript. But i want to be able to save the image paths (for all images uploaded to the database so i can be able to retrieve them for each user. Just the was facebook image upload is). The code below is in my view file.
$(document).ready(function(){
$('#profiles').change(function(){
var files = $('#profiles')[0].files;
var error = '';
var form_data = new FormData();
for(var count = 0; count<files.length; count++){
var name = files[count].name;
var extension = name.split('.').pop().toLowerCase();
if(jQuery.inArray(extension, ['gif','png','jpg','jpeg']) == -1){
error += " " + count + "Invalid Image File(s)"
}
else {
form_data.append("profiles[]", files[count]);
}
}
if(error == ''){
$.ajax({
url:"<?php echo base_url(); ?>pastors/upload_image",
method:"POST",
data:form_data,
contentType:false,
cache:false,
processData:false,
beforeSend:function() {
$('#upl_images').html("<label class='text-success'>Uploading...</label>");
},
success:function(data){
$('#upl_images').html(data);
$('#profiles').val('');
document.getElementById("success_msg").style.transition="all 0.9s ease";
document.getElementById("success_msg").style.opacity=0.5;
document.getElementById("success_msg").innerHTML="Images Successfully Uploaded";
//alert(pastor +" "+ "You saved a new report");
setTimeout(remove_prodiv, 1500);
}
})
}
else{
alert(error);
}
});
});
And this is my controller
public function upload_image(){
if($_FILES["profiles"]["name"] != ''){
$output = '';
$config["upload_path"] = './programphoto/';
$config["allowed_types"] = 'gif|jpg|png|jpeg';
$this->load->library('upload', $config);
$this->upload->initialize($config);
for($count = 0; $count<count($_FILES["profiles"]["name"]); $count++){
$_FILES["file"]["name"] = $_FILES["profiles"]["name"][$count];
$_FILES["file"]["type"] = $_FILES["profiles"]["type"][$count];
$_FILES["file"]["tmp_name"] = $_FILES["profiles"]["tmp_name"][$count];
$_FILES["file"]["error"] = $_FILES["profiles"]["error"][$count];
$_FILES["file"]["size"] = $_FILES["profiles"]["size"][$count];
if($this->upload->do_upload('file')){
$data = $this->upload->data();
//$image=$data["file_name"];
//$this->pastors_model->SaveReport($image);
$output .= '
<div class="col-md-2">
<img src="'.base_url().'programphoto/'.$data["file_name"].'" class="img-responsive img-thumbnail" />
</div>
';
}
}
echo $output;
}
}
This code uploads images perfectly to the server. but i just want a way out to saving the paths to database
I got this working.
All I did was to send the file names to the model each time it uploads,
like this:
if($this->upload->do_upload('file')){
$data = $this->upload->data();
$output .= '
<div class="col-md-2">
<img src="'.base_url().'folder/'.$data["file_name"].'" class="img-responsive img-thumbnail" />
</div>
';
$filename = $data['file_name'];
$this->Model->save_file($filename);
}

TYPO3 Extbase - Paginate through a large table (100000 records)

I have a fairly large table with about 100000 records. If I don't set the limit in the repository
Repository:
public function paginateRequest() {
$query = $this->createQuery();
$result = $query->setLimit(1000)->execute();
//$result = $query->execute();
return $result;
}
/**
* action list
*
* #return void
*/
public function listAction() {
$this->view->assign('records', $this->leiRepository->paginateRequest());
//$this->view->assign('records', $this->leiRepository->findAll());
}
... the query and the page breaks although I'm using f:widget.paginate . As per the docs https://fluidtypo3.org/viewhelpers/fluid/master/Widget/PaginateViewHelper.html I was hoping that I can render only the itemsPerPage and 'parginate' through the records ...
List.hmtl
<f:if condition="{records}">
<f:widget.paginate objects="{records}" as="paginatedRecords" configuration="{itemsPerPage: 100, insertAbove: 0, insertBelow: 1, maximumNumberOfLinks: 10}">
<f:for each="{paginatedRecords}" as="record">
<tr>
<td><f:link.action action="show" pageUid="43" arguments="{record:record}"> {record.name}</f:link.action></td>
<td><f:link.action action="show" pageUid="43" arguments="{record:record}"> {record.lei}</f:link.action></td>
</tr>
</f:for>
</f:widget.paginate>
Model:
class Lei extends \TYPO3\CMS\Extbase\DomainObject\AbstractEntity {
...
/**
* abc
*
* #lazy
* #var string
*/
protected $abc = '';
...
I use in TYPO3 9.5. The next function in repository:
public function paginated($page = 1, $size = 9){
$query = $this->createQuery();
$begin = ($page-1) * $size;
$query->setOffset($begin);
$query->setLimit($size);
return $query->execute();
}
And in the controller I am using arguments as parameter to send the page to load in a Rest action.
public function listRestAction()
{
$arguments = $this->request->getArguments();
$totalElements = $this->repository->total();
$pages = ceil($totalElements/9);
$next_page = '';
$prev_page = '';
#GET Page to load
if($arguments['page'] AND $arguments['page'] != ''){
$page_to_load = $arguments['page'];
} else {
$page_to_load = 1;
}
#Configuration of pagination
if($page_to_load == $pages){
$prev = $page_to_load - 1;
$prev_page = "http://example.com/rest/news/page/$prev";
} elseif($page_to_load == 1){
$next = $page_to_load + 1;
$next_page = "http://example.com/rest/news/page/$next";
} else {
$prev = $page_to_load - 1;
$prev_page = "http://example.com/rest/news/page/$prev";
$next = $page_to_load + 1;
$next_page = "http://example.com/rest/news/page/$next";
}
$jsonPreparedElements = array();
$jsonPreparedElements['info']['count'] = $totalElements;
$jsonPreparedElements['info']['pages'] = $pages;
$jsonPreparedElements['info']['next'] = $next_page;
$jsonPreparedElements['info']['prev'] = $prev_page;
$result = $this->repository->paginated($page_to_load);
$collection_parsed_results = array();
foreach ($result as $news) {
array_push($collection_parsed_results, $news->parsedArray());
}
$jsonPreparedElements['results'] = $collection_parsed_results;
$this->view->assign('value', $jsonPreparedElements);
}
The result of this, is a JSON like this:
{
"info": {
"count": 25,
"pages": 3,
"next": "",
"prev": "http://example.com/rest/news/page/2"
},
"results": [
{ ....}
] }
How large / complex are the objects you want to paginate through? If they have subobjects that you dont need in the list view, add #lazy annotation to those relations inside the model.
Due to this large amount of records, you should keep them as simple as possible in the list view. You can try to only give the result as array to the list view using $this->leiRepository->findAll()->toArray() or return only the raw result from your repository by adding true to execute(true).
You can also create an array of list items yourself in a foreach in the controller and only add the properties you really need inside the list.
If your problem is the performance, just use the default findAll()-Method.
The built-in defaultQuerySettings in \TYPO3\CMS\Extbase\Persistence\Repository set their offset and limit based on the Pagination widget, if not set otherwise.
If the performance issue persists, you may have to consider writing a custom query for your database request, that only requests the data your view actually displays. The process is described in the documentation: https://docs.typo3.org/typo3cms/ExtbaseFluidBook/6-Persistence/3-implement-individual-database-queries.html

How put dates on flot

I've a little problem, I need to do a curve with on y axis numbers and x axis dates.. but I can't display some dates...
My code :
<script type="text/javascript">
$(function () {
<?php
echo " var data = [";
$cpt="0";
include ('../connect.php');
// Requete SQL
$req = 'select "SPP_NB_IND" from "STAT_PERPHY" where "SPP_SAGES" = \''.$sages.'\' AND "SPP_DATE" between \''.$jourtableau.' 00:00:00\' and \''.$jourfinw.' 23:59:59\'';
$res = pg_query($req);
$reqd = 'select "SPP_DATE" from "STAT_PERPHY" where "SPP_SAGES" = \''.$sages.'\' AND "SPP_DATE" between \''.$jourtableau.' 00:00:00\' and \''.$jourfinw.' 23:59:59\' AND "SPP_NB_IND" IS NOT NULL ';
$resd = pg_query($reqd);
// On met les valeurs obtenues dans un tableau
while ( $row = pg_fetch_assoc ($res) )
{
//echo $row['SPP_NB_IND']."<br>";
$var=$row['SPP_NB_IND'];
while ( $roww = pg_fetch_assoc ($resd) )
{
$abscisse=date('d-m', strtotime($roww['SPP_DATE']));
}
echo "[$abscisse, $var],";
$cpt++;
}
echo "];";
?>
var options = {
lines: {
show: true
},
points: { show: true
},
xaxis: {
mode: "time",
timeformat : "%d/%m"
}
};
<?php
echo "$.plot($(\"#graph1\"), [ data ], options);";
?>
});
</script>
[/CODE]
When I put $abscisse, my curve is vertical and if I put $cpt, I have a "normal" curve... but I want to see dates corresponding with numbers..
Freindly,
Tanaes.
See the documentation:
You have to give flot timestamps, not already formated dates. For PHP use something like
$abscisse = strtotime($roww['SPP_DATE']) * 1000;

Fixing code to fetch data from dom document (getElementby...)

url : sayuri.go.jp/used-cars
$content = file_get_contents('http://www.sayuri.co.jp/used-cars/');
$dom = new DOMDocument;
$dom->loadHTML($content);
Partial Source code :
<td colspan="4">
<h4 class="stk-title">Toyota Wish G</h4>
</td>
<td colspan="4">
I am trying to go through the source code and for each parts of the above i want to save the url e.g : "/used-cars/B37753-Toyota-Wish-japanese-used-cars"
Here is the code i am using but unsuccessful so far
$p = $dom->getElementsByTagName("h4");
$titles = array();
foreach ($p as $node) {
if ($node->hasAttributes()) {
if($node->getAttribute('class') == "stk-title") {
foreach ($node->attributes as $attr) {
if ($attr->nodeName == "href") {
array_push($titles , $attr->nodeValue);
}
}
}
}
}
print_r($titles) ;
It should give me an array containing all the urls of each car : ("/used-cars/B37753-Toyota-Wish-japanese-used-cars" , "" , "" ......)
but its returning an empty array - i guess i made a mistake in my code and it can't access the urls.
I also need to save the car name inside a variable e.g : $car_name = "Toyota Wish G"
Use XPath:
$doc = new DOMDocument;
$doc->loadHTMLFile('http://www.sayuri.co.jp/used-cars/');
$xpath = new DOMXPath($doc);
$nodes = $xpath->query('//table[#class="itemlist-table"]//h4[#class="stk-title"]/a');
$links = array();
foreach ($nodes as $node) {
$links[] = array(
'href' => $node->getAttribute('href'),
'text' => $node->textContent,
);
}
print_r($links);

Symfony Zend Lucene Search Multiple Tables

I have a Symfony project and I used Zend Lucene Search framework to integrate a search on the site. It works beautifully but it's limited to searching 1 table.
I need my users to be able to search the whole site (8 select tables) and return the results all together. Each table has the same fields indexed. This is the code that specifies the table and calls the query.
Is there a way to make it look through all 8 tables for results?
public function getForLuceneQuery($query)
{
$hits = self::getLuceneIndex()->find($query);
$pks = array();
foreach ($hits as $hit)
{
$pks[] = $hit->pk;
}
if (empty($pks))
{
return array();
}
$alltables = Doctrine_Core::getTable('Car');
$q = $alltables->createQuery('j')
->whereIn('j.token', $pks)
->orderBy('j.endtime ASC')
->andwhere('j.endtime > ?', date('Y-m-d H:i:s', time()))
->andWhere('j.activated = ?', '1')
->limit(21);
return $q->execute();
}
To give a bit of background on the 8 tables, they are all basically similar. They all have title, make, model, etc so I need to run a single query on all of them and return all results (regardless of which table it is in) in Ascending order. The Doctrine_core::getTable command doesn't seem to like multiple tables or even arrays (unless I'm not doing it right). Thanks!
UPDATE (WORKING):
Here is the updated code. This is what I have in the SearchTable.class.php file:
public function getForLuceneQuery($query)
{
// sort search result by end time
$hits = self::getLuceneIndex()->find(
$query, 'endtime', SORT_NUMERIC, SORT_ASC
);
$result = array(
'index' => $hits,
'database' => array(),
);
// group search result by class
foreach ($hits as $hit)
{
if (!isset($result['database'][$hit->class]))
{
$result['database'][$hit->class] = array();
}
$result['database'][$hit->class][] = $hit->pk;
}
// replace primary keys with real results
foreach ($result['database'] as $class => $pks)
{
$result['database'][$class] = Doctrine_Query::create()
// important to INDEXBY the same field as $hit->pk
->from($class . ' j INDEXBY j.token')
->whereIn('j.token', $pks)
->orderBy('j.endtime ASC')
->andwhere('j.endtime > ?', date('Y-m-d H:i:s', time()))
->andWhere('j.activated = ?', '1')
->limit(21)
->execute();
}
return $result;
}
Here is what I have in the actions.class.php file for the Search Module:
public function executeIndex(sfWebRequest $request)
{
$this->forwardUnless($query = $request->getParameter('query'), 'home', 'index');
$this->results = Doctrine_Core::getTable('Search')
->getForLuceneQuery($query);
}
And finally this is my template file indexSuccess.php I have simplified it so it's easier to understand. My indexSuccess.php is more complicated but now that I can call the values, I can customize it further.
<div class="product_list"
<ul>
<?php foreach ($results['index'] as $hit): ?>
<li class="item">
<?php if (isset($results['database'][$hit->class][$hit->pk])) ?>
<span class="title">
<?php echo $results['database'][$hit->class][$hit->pk]->getTitle() ?>
</span>
</li>
<?php endforeach ?>
</ul>
</div>
This works beautifully. I was able to customize it by calling each of the fields in the search results and it works perfect. I added an item to each of the tables with the same title and the search result pulled them all. Thank you so much!
OK. I'll try to give you some hint, with code :)
First of all you should add these fields to the index:
$doc->addField(Zend_Search_Lucene_Field::Keyword('class', get_class($record)));
$doc->addField(Zend_Search_Lucene_Field::UnIndexed('endtime', strtotime($record->get('endtime'))));
Than you should use these new fields:
public function getForLuceneQuery($query)
{
// sort search result by end time
$hits = self::getLuceneIndex()->find(
$query, 'endtime', SORT_NUMERIC, SORT_ASC
);
$result = array(
'index' => $hits,
'database' => array(),
);
// group search result by class
foreach ($hits as $hit)
{
if (!isset($result['database'][$hit->class]))
{
$result['database'][$hit->class] = array();
}
$result['database'][$hit->class][] = $hit->pk;
}
// replace primary keys with real results
foreach ($result['database'] as $class => $pks)
{
$result['database'][$class] = Doctrine_Query::create()
// important to INDEXBY the same field as $hit->pk
->from($class . ' j INDEXBY j.token')
->whereIn('j.token', $pks)
->orderBy('j.endtime ASC')
->andwhere('j.endtime > ?', date('Y-m-d H:i:s', time()))
->andWhere('j.activated = ?', '1')
->limit(21)
->execute();
// if you want different query per table
// you should call a function which executes the query
//
// if (!method_exists($table = Doctrine_Core::getTable($class), 'getLuceneSearchResult'))
// {
// throw new RuntimeException(sprintf('"%s::%s" have to be exists to get the search results.', get_class($table), 'getLuceneSearchResult'));
// }
//
// $results[$class] = call_user_func(array($table, 'getLuceneSearchResult'), $pks);
}
return $result;
}
After that in the template you should iterate over $result['index'] and display results from $result['database']
foreach ($result['index'] as $hit)
{
if (isset($result['database'][$hit->class][$hit->pk]))
{
echo $result['database'][$hit->class][$hit->pk];
}
}
And there are same alternate (maybe better) solutions that I can think of:
Alternate solution #1:
You can store data in the index and this data will be accessible in the search result. If you not need too much data when displaying the results and can update the index frequently I think this is a good option. This way you can use pagination and no SQL queries needed at all.
$doc->addField(Zend_Search_Lucene_Field::Text('title', $content->get('title')));
...
$hit->title;
Alternate solution #2:
As you wrote, your tables are very similar, so you maybe could use column aggregation inheritance. In this way all data stored in one table so you can query them all together and can order and paginate as you want.