I have a product search page. In which I have search field. After searching the list of product is displaying in result section. Now I want to modify the search using left side panel "Refine your search" , in this section there are some parameter that will narrow your search.
Let user searching Shirt then my URL is http://localhost:8080/query?q=shirt
Now if user refine the result with color RED. I need to update the URL with
http://localhost:8080/query?q=shirt&color=red
How to do ?
I am using Spring MVC and JSP , Javascript is also an option.
If you aren't adverse to using jQuery, then you can implement this. It doesn't completely account for the actual search query though since I don't fully know your implementation.
var currentColor = '';
$("input[type=radio]").on('click', function () {
var previousColor = currentColor;
currentColor = $(this).val();
//if the parameter has already been set then replace, otherwise create a new one
if (previousColor) {
location.href = location.href.replace("color=" + previousColor, "color=" + currentColor);
} else {
location.href = location.href + '&color=' + currentColor;
}
});
Related
I have a webpage that has a dynamic search field that will query a database as you type in the search string (much like a google search with suggestions as you type). This part works via AJAX.
In the results, there are multiple rows of data that are displayed below as data is entered into the search field. What I decided to do is create an edit link on the right side of each row (with pencil icon) that is returned by ajax so I can click to another page for editing the data. Something like this...
<a href="edit.php?id=12&search=Goodyear"><i class="fa fa-pencil" aria-
hidden="true"></i></a>
So lets say that I searched for "Goodyear" in the example search and on row 12, I click the link that takes me to another page. I was wanting to use $_GET["search"] to turn around and create a BACK link to the original AJAX page. I know how to get this far, however, I need help customizing the ajax to reload the original search (which in this example is "Goodyear") when the link is clicked back to the search page. The link on the EDIT page would look something like:
Back to Search Page
But here is the issue. When the user returns, I need the search bar prefilled and the search results listed below. In other words, I want the page to be just like it was when they left prior to going to the edit page. I want AJAX to search the search again on page load just because it visited this url /search.php?search=Goodyear Making the url in the link on the edit page is not a problem for me. But it is when it is clicked to return to original search page.
Here is the AJAX code that does all the heavy lifting on the search.php page.
<script>
$(document).ready(function () {
load_data();
function load_data(query) {
$.ajax({
url: "search.php",
method: "POST",
data: { query: query },
success: function (data) {
$('#brand').html(data);
}
});
}
$('#search_text').keyup(function () {
var search = $(this).val();
if (search != '') {
load_data(search);
}
else {
load_data();
}
});
});
</script>
I know that this search happens on a keyup event and the div called #brand displays the resulting rows of data below the search bar. It actually works well just on the search alone, but leaving the page and clicking back with a url (search.php?search="goodyear") like I mentioned is not doing what I need it to.
When I try to modify it, the search results stop showing. .
I have tried to customize this code to process the url using GET variable within this code that uses POST in the AJAX but I have been been unsuccessful so far. Any ideas on what I need to do?
I found the original page I originally used to make my search page.. here it if anyone wants to look: http://www.webslesson.info/2016/03/ajax-live-data-search-using-jquery-php-mysql.html
This may not be the perfect answer but it does work pretty nicely. Although the only thing it does not do is show the text in the search field when you return to the page. If anyone know how, give the answer... but this is what I did...
I found a nice piece of code that strips out the value of the parameter in the url and then throws it into an array variable. I found it on http://www.designchemical.com/blog/index.php/jquery/8-useful-jquery-snippets-for-urls-querystrings/. Here is the code.
var vars = [], hash;
var q = document.URL.split('?')[1];
if(q != undefined){
q = q.split('&');
for(var i = 0; i < q.length; i++){
hash = q[i].split('=');
vars.push(hash[1]);
vars[hash[0]] = hash[1];
}
}
load_data(vars['search']);
search is the parameter in the url and if it says search.php?search=255 then it returns 255. So I threw that into the load_data argument value and it does the search. The only drawback so far is I haven't figured out how to make the value show in the search bar. I'll keep plugging.
UPDATE: I figured out the text in search box issue with this code:
$('input[name="search_text"]').val(vars['search']);
It put the search parameter back into the search input field like I wanted! One more note, be sure to put the above code above the load_data(vars['search']); may not matter but that is what I did to make it work!
This is what it looked like:
var vars = [], hash;
var q = document.URL.split('?')[1];
if(q != undefined){
q = q.split('&');
for(var i = 0; i < q.length; i++){
hash = q[i].split('=');
vars.push(hash[1]);
vars[hash[0]] = hash[1];
}
}
$('input[name="search_text"]').val(vars['search']);
load_data(vars['search']);
Background: I have little knowledge of javascript, only html and css.
My Problem: I have a dynamic table on my webpage (WPDataTables) that includes a global search and then column specific search. My users can type into these searches and the content will dynamically update. My problem is the URL does not update to include search parameters so we cannot copy and send URL's to other people that include specific search results.
WpDataTables currently has the following keys to pre filter the table:
Global: ?wdt_search=filtervalue
Column: ?wdt_column_filter[ColumnName]=filtervalue
This is great but my users aren't savvy enough to create their own URL strings and there are a large number of possible filters so pre-creating each one is not an option.
Currently: I am close to getting a solution, I think, with the following:
<body>
<button onclick="updateURL();">Update</button>
<script type="text/javascript">
function updateURL() {
if (history.pushState) {
var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?para=hello';
window.history.pushState({path:newurl},'',newurl);
}
}
</script>
</body>
Ideally, with this the user will simply click the Update button to update the URL with the current search parameters. The problem is ?para=hello is just a hard coded parameter and I can't figure out how to get it to be dynamic and change with the users searching/filtering.
My website: http://imsched.com/sailings
The query string can't be updated without reloading the page. If you want to track those updates in the url so they are shareable, and still have them affect your filters you could use the hash instead. The hash can be easily read and you can update it without reloading the page.
// to read
window.location.hash
// to update
window.location.hash = 'param=value¶m=value'
If you had a url like this http://url.com#1=one&2=two&3=three, you could do the following:
var filters = window.location.hash.split('&')
// filters now = ['1=one', '2=two', '3=three']
// so you can make easy use of those
Update
If you need to update the query string and don't mind that it reloads the page each time, you can manipulate it via window.location.search
// to read
window.location.search
// to update (will reload the page)
window.location.search = window.location.search + '&your_stuff=here'
A function that could build your query string from your filter fields could look like this:
function buildQuery() {
var inputs = [].slice.call(document.querySelectorAll('.js-filter'))
return inputs.reduce(function(str, el, i) {
return str + (i > 0 ? '&' : '') + el.name + '=' + el.value
}, '')
}
Example fiddle here
You can try use HTML5 History Manipulation:
https://css-tricks.com/using-the-html5-history-api/
It's more commom with AngularJS, etc...
Sorry, the above solution didn't work for me you can try this:
window.location.pathname.replace(/[^a-zA-Z ]/, "");
I am new to Javascript and C# and wanted to know how to get search box id of the search box present on website.
Kindly refer the approach i followed
var url = "example.com";
System.Net.WebRequest req = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
if (res.StatusCode == HttpStatusCode.OK)
{
<script type="text/javascript">
function searchAlive() {
var link_s = document.getElementById('search').value;
}
</script>
}
You can get the search box id by using Javascript/Jquery using some properties(css,text etc..) of the text box. include html so that we can help you better
If you want use JavaScript:
var _Searched = document.getElementById("SearchTextBoxID").val();
if you are using C#:
string _Searched = SearchTextBoxID.text;
you have to show your codes and your approach. what environment you are coding in and what language you are using ?
If you mean you don't know the "SearchBoxInput" ID and you want to get it, you can use other element such as the class name or tag name to get the element value. But as a programmer, you have to know and work with 'ID' when using backend codes like c# and javascript.
if you want to get the id:
var inputs = document.getElementByTagName("input");
for(i=0;i<=inputs.lenght;i++){
if(inputs[i].class == "searchClass"){ var id = input[i].id }
}
I am working on a Name Game type of Name Generator where you enter some fields and associated variables are pulled. I have the generator working and the share links working, however I can't get them to populate with the final 'sillyname' variable.
AKA When you click share, it has a generic message but I am trying to get it to dynamically enter the name into the tweet or facebook share text.
Any help on this would be awesome.
Here is the link for you to dig deeper.
http://codepen.io/drewlandon/pen/VLvpjq
I have this in the twitter/facebook share function:
var twitterWindow = window.open('https://twitter.com/intent/tweet?url=http://sweetleafmarijuana.com/&text=My Sweet and Fierce Name... &via=TheSweetestLeaf &hashtags=SweetFierceName', 'twitter-popup', 'height=350,width=600'); if(twitterWindow.focus) { twitterWindow.focus(); }
return false; } var facebookShare = document.querySelector('[data-js="facebook-share"]');
However I found this and feel like it needs to be something along these lines:
function twitterShare(){
var shareText='My funny pseudonym is '+accents_to_regulars(outputName)+', according to #...'
So i'm thinking i need something like this (but having trouble from there)
var twitterMessage = "My #SWEETFIERCENAME is " + hungryName + ", according to #thesweetestleaf's #SweetFierceName Name Generator";
var facebookMessage = "My name is " + hungryName + "";
You need to escape the text for the URL.
It works here: http://codepen.io/anon/pen/Kpdvqa
twitterShare.onclick = function(e) {
e.preventDefault();
var twitterWindow = window.open('https://twitter.com/intent/tweet?url=http://sweetleafmarijuana.com/&text='+encodeURIComponent(getSillyName())+'&via=TheSweetestLeaf &hashtags=SweetFierceName', 'twitter-popup', 'height=350,width=600');
if(twitterWindow.focus) { twitterWindow.focus(); }
return false;
}
The # character has special meaning in URLs.
As for the Facebook message, there is no way to pre-fill that anymore:
http://www.quora.com/With-Facebooks-share-link-is-there-a-way-to-prefill-the-text-to-be-posted
You will have to take a closer look at the FB Feed Dialog to see other options, like perhaps updating the caption property instead.
I am working on a feature for my site that allows the user to use the back button and not have to load more database results.
I start by loading 16 results, and then there is a load more button which loads the next 16. In the ajax success i change the href of this button so the url changes to e.g. domain.com/#1 to #2.
I wrote this last night:
// First get the page URL and split it via # signs
var parts = location.href.split('#');
// now we run a check on the URL and see how many 'parts' there are
if(parts.length > 1)
{
var params = parts[0].split('?');
var mark = '?';
if(params.length > 1)
{
mark = '&';
}
location.href = parts[0] + mark + 'page=' + parts[1];
}
Which gets the URL, and redirects the user the same page but converts the fragment number to a page number. From this i then use a PHP $_GET and set the limit claus last value from that.
This works fine. But its primitive. Let for instance say i push back and the URL becomes:
www.domain.com/?page=1
If i then click to load some more data, the page url becomes:
www.domain.com/?page=1#2
If the user then visits another page and comes back then they get directed to:
www.domain.com/?page=1&page=1
Whats the best way around this? I was thinking of running a check on the URL at the same time as looking for a fragment and if the URL has a page variable i then add that variable to the fragment variable and the page URL becomes ?page=THE SUM NUMBER
Any help on modifying the snippet i posted above to check the URL for a page value and then add the two together before the redirection?
Thanks!
You need to use location.search to get the query string on a URL:
var queryParameters = location.search.split('&');
Then you can loop through the queryParameters and check if page is set:
var pageNumber = 0;
for(var i = 0; i < queryParameters.length; i++)
{
var keyvaluePair = queryParameters[i].split('=');
if(keyvaluePair[0] == 'page')
{
pageNumber = keyvaluePair[1];
break;
}
}
Please see the documentation on the MDN:
https://developer.mozilla.org/en-US/docs/Web/API/Window.location
You might also find this example useful for returning one value:
https://developer.mozilla.org/en-US/docs/Web/API/Window.location#Example_.236.3A_Get_the_value_of_a_single_window.location.search_key.3A
If you want to get the information after the #, you need to use location.hash. The MDN documentation I linked also has information on location.hash.