Opencart 1.5.4 Search by Description - search

I have read various entries about searching by description and subcategories in opencart by default but I have a unique problem. I have two header files because my site has 2 headers... one for the home page and one for every other page.
Home Page:
https://garrysun.com/
Other Page:
https://garrysun.com/ayurveda-products/categories
When I search on the home page I get the correct results (search the word "heart") but when I search any other page it doesn't return the search for descriptions or subcategories.
Home Page Search Results:https://garrysun.com/index.php?route=product/search&filter_description=true&filter_sub_category=true&filter_name=heart
Other Page Search Results:https://garrysun.com/index.php?route=product/search&filter_name=heart
As you can see, when I search the other page the extra code is not being added to search in descriptions and subcategories.
So why is this new code that I added working for the home page an not any other page?
To make this search function work I have changed the common.js file to look like this (adding the two lines below each "url= $(base..." section:
/* Search */
$('.button-search').bind('click', function() {
url = $('base').attr('href') + 'index.php?route=product/search';
url += '&filter_description=true'; // ADDED this to search descriptions
url += '&filter_sub_category=true'; // ADDED this to search sub-categories
var filter_name = $('input[name=\'filter_name\']').attr('value');
if (filter_name) {
url += '&filter_name=' + encodeURIComponent(filter_name) ;
}
location = url;
});
$('#header input[name=\'filter_name\']').bind('keydown', function(e) {
if (e.keyCode == 13) {
url = $('base').attr('href') + 'index.php?route=product/search';
url += '&filter_description=true'; // ADDED this to search descriptions
url += '&filter_sub_category=true'; // ADDED this to search sub-categories
var filter_name = $('input[name=\'filter_name\']').attr('value');
if (filter_name) {
url += '&filter_name=' + encodeURIComponent(filter_name) ;
}
location = url;
}
});
Both header files use the same code to call the search function:
<div id="search">
<div class="button-search"></div>
<?php if ($filter_name) { ?>
<input type="text" name="filter_name" value="<?php echo $filter_name; ?>" />
<?php } else { ?>
<input type="text" name="filter_name" value="<?php echo $text_search; ?>" onclick="this.value = '';" onkeydown="this.style.color = '#000000';" />
<?php } ?>
</div>
</div>

After trying to figure out what's wrong in your code for few minutes (unsuccessfully), I ran a network debugging and found out that nothing is wrong with your code, you are just calling 2 different Javascript files(!):
On your home page, you are using common.js that is located at https://garrysun.com/catalog/view/javascript/common.js.
On your category pages, you are using common.js that is located at https://garrysun.com/catalog/view/javascript/add2cart-go2cart/common.js.
The 2nd one does not include your modifications, and looks like this:
$('.button-search').bind('click', function() {
url = $('base').attr('href') + 'index.php?route=product/search';
var filter_name = $('input[name=\'filter_name\']').attr('value');
if (filter_name) {
url += '&filter_name=' + encodeURIComponent(filter_name);
}
location = url;
});
$('#header input[name=\'filter_name\']').bind('keydown', function(e) {
if (e.keyCode == 13) {
url = $('base').attr('href') + 'index.php?route=product/search';
var filter_name = $('input[name=\'filter_name\']').attr('value');
if (filter_name) {
url += '&filter_name=' + encodeURIComponent(filter_name);
}
location = url;
}
});
Vuala.
Hope this helps!

Related

Show the item hit content only when the search box is not empty

I have this in my algolia file for my jekyll site.
<script>
const search = instantsearch({
appId: '{{ site.algolia.application_id }}',
apiKey: '{{ site.algolia.search_only_api_key }}',
indexName: '{{ site.algolia.index_name }}',
searchParameters: {
restrictSearchableAttributes: [
'title',
'content'
],
facetFilters: ['type:post']
},
});
const hitTemplate = function(hit) {
let date = '';
if (hit.date) {
date = moment.unix(hit.date).format('L');
// date = moment.unix(hit.date).format('MMM Do YY');
modifiedDate = moment.unix(hit.last_modified_at).format('MMM Do YY');
}
const url = hit.url;
const title = hit._highlightResult.title.value;
const content = hit._highlightResult.html.value;
return `
<div class="post-list">
<span class="post-date-list-wrap">
<span class="post-date-list">${date}
<span class="post-title"> ${title} </span>
</span>
${content}
</div>
`;
}
const hitTemplateTrans = function(hit) {
let date = '';
if (hit.date) {
date = moment.unix(hit.date).format('MMM DD YYYY');
}
const url = hit.url;
const title = hit._highlightResult.title.value;
const content = hit._highlightResult.html.value;
return `
<div class="post-list">
<span class="post-date-list-wrap">
<span class="post-date-list">${date}
<span class="post-title"> ${title}</span>
</span>
</span>
</div>
`;
}
search.addWidget(
instantsearch.widgets.searchBox({
container: '#search-searchbar',
placeholder: 'search notes',
autofocus: true
})
);
search.addWidget(
instantsearch.widgets.hits({
container: '#search-hits',
templates: {
empty: 'No results',
item: hitTemplate
},
})
);
search.start();
</script>
Without typing anything in the search box I have the list of articles
with the excerpt, the short introduction of the article.
That's because I have ${content} to show the highlights when someone
types the search term.
That's fine and everything is working but... I don't want to show the contents of each item when the search box is empty.
If the search box is empty I would like to keep only the title and the date
but if the search box is not empty just show the title/date and the excerpt as it's usual.
It seems like an easy task but I'm stuck right now, I tried removed the content tag and put in the hit transformation function, but it doesn't work.
The instantsearch.js library has a function hook, called searchFunction, you can define when instanciating the library. That is called right before any search is performed. You can use it to check if the current query is empty or not, and adapt your layout based on this knowledge.
Here is a slightly edited script (irrelevant parts removed) that should let you do what you're looking for:
let additionalClass = '';
const search = instantsearch({
[…]
searchFunction: function(helper) {
if (helper.getState().query === '') {
additionalClass = 'post-item__empty-query';
} else {
additionalClass = '';
}
helper.search()
}
});
[…]
const hitTemplate = function(hit) {
return
`<div class="post-item ${additionalClass}">
[…]
</div>`
;
}
.post-item__empty-query .post-snippet {
display: none;
}
What it does is defining a global variable (additionalClass) that will be used in the hit template (added alongside item-post, at the root level).
Right before everysearch, we check if the query is empty. If so, we set additionalClass to item-post__empty_query. We also defined in CSS that when this class is applied, the content should be hidden.
All of that together makes the title + date displayed when no search is performed, and the content displayed only when an actual keyword is searched for.
Hope that helps,

handling JSOM clientcontext properly

I am trying out JSOM in Sharepoint 2016. I have made a WebPart containing the following code -
<div id="user-output"></div>
Movie Title: <input type="text" id="movie-title" /><br />
Description: <input type="text" id="movie-description" /><br />
<button type="button" id="submit-button">Add Movie</button>
<div id="movies-output"></div>
<script type="text/javascript" src="/SiteAssets/jquery-3.2.1.min.js"></script>
<script type="text/ecmascript" src="../_layouts/15/SP.UserProfiles.js"></script>
<script type="text/javascript">
$(function () {
$('#submit-button').on('click', function () {
var context = SP.ClientContext.get_current();
var movies = context.get_web().get_lists().getByTitle('Movies');
var movieCreationInfo = new SP.ListItemCreationInformation();
var movie = movies.addItem(movieCreationInfo);
movie.set_item("Title", $('#movie-title').val());
movie.set_item("MovieDescription", $('#movie-description').val());
movie.update();
context.load(movie);
context.executeQueryAsync(success, failure);
});
function success() {
$('#movies-output').text('Created movie!');
}
function failure() {
$('#movies-output').text('Something went wrong');
}
var upp;
// Ensure that the SP.UserProfiles.js file is loaded before the custom code runs.
//SP.SOD.executeOrDelayUntilScriptLoaded(getUserProperties, 'SP.UserProfiles.js');
SP.SOD.executeFunc('userprofile', 'SP.UserProfiles.PeopleManager', getUserProperties);
//SP.SOD.executeFunc('SP.UserProfiles.js', getUserProperties);
function getUserProperties() {
// Get the current client context and PeopleManager instance.
var clientContext = new SP.ClientContext.get_current();
var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
upp = peopleManager.getMyProperties();
clientContext.load(upp, 'UserProfileProperties');
clientContext.executeQueryAsync(onRequestSuccess, onRequestFail);
}
// This function runs if the executeQueryAsync call succeeds.
function onRequestSuccess() {
$('#user-output').html('User Name: ' + upp.get_userProfileProperties()['PreferredName'] +
'<br/>Department: ' + upp.get_userProfileProperties()['Department'] +
'<br/>Designation: ' + upp.get_userProfileProperties()['Title'] +
'<br/>Employee ID: ' + upp.get_userProfileProperties()['EmployeeID'] +
'<br/>Branch Code: ' + upp.get_userProfileProperties()['branchCode']
);
}
// This function runs if the executeQueryAsync call fails.
function onRequestFail(sender, args) {
$('#user-output').text("Error: " + args.get_message());
}
});
What this code does is -
Show user information in user-output div at document load ready
Saves a movie record when Add Movie button is clicked
However, for some reason, when Add Movie button is clicked, the code adds two movies instead of one. I think it has something to do with the ClientContext. But I am not sure why, or how to solve it. Can anyone help?
I am not sure how it happened, or if it's a bug, but while fiddling with the page source to find out why double posting was occurring, I saw that my web part code was being rendered twice in the page. One part was visible, and another was under a hidden div. However, when I went to edit page to delete the hidden web part, I couldn't. So I restored my page to the template version and re-added the web part. After that the web part was working correctly. There were no problems with the code.

How to get textbox value in Action in asp.net MVC 5

I want to send the value of textbox to the Action Method for searching the technology for that i want to get the value of textbox in Action.
I have the following code :-
#Html.TextBox("technologyNameBox", "", new { id = "technologyName", #class = "form-control", #placeholder = "Search For Technology" })
<span class="input-group-btn" style="text-align:left">
<a class="btn btn-default" id="searchTechnology"
href="#Url.Action("SearchTechnology", "Technology",
new {technologyName="technologyName",projectId=ProjectId })">
<span class="glyphicon glyphicon-search "></span>
</a>
</span>
Question :- How to get the value of textbox "technologyNameBox" in Action ?
Please help me out. Thanks in Advance!
You'd have to append the value to the URL via JavaScript before directing the user. Using jQuery (since that generally comes packaged with ASP.NET), it might look something like this (with a good bit of manual conditional checks for blank values or query string parameters):
$('#searchTechnology').click(function (e) {
e.preventDefault();
var url = '#Url.Action("SearchTechnology", "Technology", new { projectId=ProjectId })';
var technologyName = $('#technologyName').val();
if (technologyName.length < 1) {
// no value was entered, don't modify the url
window.location.href = url;
} else {
// a value was entered, add it to the url
if (url.indexOf('?') >= 0) {
// this is not the first query string parameter
window.location.href = url + '&technologyName=' + technologyName;
} else {
// this is the first query string parameter
window.location.href = url + '?technologyName=' + technologyName;
}
}
return false;
});
The idea is that when the user clicks that link, you would fetch the value entered in the input and append it to the URL as a query string parameter. Then redirect the user to the new modified URL.

Meteor Facebook Profile Picture not Displaying

On first sign I have the following code:
Accounts.onCreateUser(function(options,user){
if (typeof(user.services.facebook) != "undefined") {
user.services.facebook.picture = "http://graph.facebook.com/" + user.services.facebook.id + "/picture/?type=large";
}
return user;
});
Which results in the following URL string
http://graph.facebook.com/[myfacebookid]/picture/?type=large
Yet when it renders that url and returns
<img scr="http://graph.facebook.com/[myfacebookid]/picture/?type=large" alt="My Name">
All I see is a broken image. How can I pull this in so that it renders the facebook profile picture?
I use a helper function based off of the Facebook ID of the user to grab the image on the server. I notice my url has /picture? and your has /picture/? Hope this helps.
userPicHelper: function() {
if (this.profile) {
var id = this.profile.facebookId;
var img = 'http://graph.facebook.com/' + id + '/picture?type=square&height=160&width=160';
return img;
}
},
I don't know how I missed this before, but is this the src attribute on the image tag is actually written as scr:
<img scr=
Should be...
<img src=
You have http instead of https.
So:
"https://graph.facebook.com/" + id + "/picture/?type=large";
This was my problem.

Greasemonkey: Re-write all links based on param

I need alittle help with getting a script that will take param from the orginal link and re-write them into a new link. I guess it should be pretty easy but I'm a noob still when it comes to this.
Here is the orginal HTML code for 1 link. (should be replaced globaly on the page. image1.jpg, image2.jpg etc.)
<div align="center"><img src="/preview/image1.jpg" width="128" height="128" border="0" style="border: 0px black solid;" /></div>
This should be done global on all the links that contain the imagepath "/preview/"
Thanks to Brock Adams I kinda understand how to get the param values with this code but I still don't really get it how to re-write all the links in a page.
var searchableStr = document.URL + '&';
var value1 = searchableStr.match (/[\?\&]id=([^\&\#]+)[\&\#]/i) [1];
var value2 = searchableStr.match (/[\?\&]connect=([^\&\#]+)[\&\#]/i) [1];
and then rewrite the links with "newlink"
var domain = searchableStr.match (/\/\/([w\.]*[^\/]+)/i) [1];
var newlink = '//' + domain + '/' + value1 + '/data/' + value2 + '.ext';
If someone could be so nice to help me setup an example greasemonkey script I would be very greatful for it.
OK, This is a fairly common task and I don't see any previous, Stack Overflow questions like it -- at least in a 2 minute search.
So, here's a script that should do what you want, based on the information provided...
// ==UserScript==
// #name Site_X, image relinker.
// #namespace StackOverflow
// #description Rewrites the preview links to ???
// #include http://Site_X.com/*
// #include http://www.Site_X.com/*
// #include https://Site_X.com/*
// #include https://www.Site_X.com/*
// ==/UserScript==
function LocalMain () {
/*--- Get all the images that have /preview/ in their path.
*/
var aPreviewImages = document.evaluate (
"//img[contains (#src, '/preview/')]",
document,
null,
XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,
null
);
var iNumImages = aPreviewImages.snapshotLength;
GM_log (iNumImages + ' preview images found.');
/*--- Rewrite the parent links to our new specifications.
Note, all the target links are of the form:
<a href="/index.php?Submit=ok&seson=b1e4&connect=127.0.0.1&id=13033&name=on">
<img src="/preview/image1.jpg" width="128" height="128" border="0" style="border: 0px black solid;" />
</a>
The desired rewrite changes the link to this form:
<a href="{current page's domain}/{id-value}/data/{connect-value}.ext">
*/
for (var iLinkIdx=0; iLinkIdx < iNumImages; iLinkIdx++) {
var zThisImage = aPreviewImages.snapshotItem (iLinkIdx);
var zParentLink = zThisImage.parentNode;
//--- Get the key href parameters.
var sIdValue = sGetUrlParamValue (zParentLink, 'id');
if (!sIdValue) continue; //-- Oopsie, this link was a malformed.
var sConnectValue = sGetUrlParamValue (zParentLink, 'connect');
if (!sConnectValue) continue;
//--- Get the current page's domain. (Or just use a relative link.)
var sPageDomain = document.URL.match (/\/\/([w\.]*[^\/]+)/i) [1];
//--- Generate the desired link value.
var sDesiredLink = 'http://' + sPageDomain + '/' + sIdValue + '/data/' + sConnectValue + '.ext';
//--- Rewrite the target link.
zParentLink.href = sDesiredLink;
}
}
function sGetUrlParamValue (zTargLink, sParamName) {
var zRegEx = eval ('/[\?\&]' + sParamName + '=([^\&\#]+)[\&\#]/i');
var aMatch = (zTargLink.href + '&').match (zRegEx);
if (aMatch)
return decodeURI (aMatch[1]);
else
return null;
}
window.addEventListener ("load", LocalMain, false);

Resources