Adding search criteria to the url, but can't go back - javascript

I'm trying to get the parameters of my search criteria into the url so that it's possible to copy and paste the specific search.
Currently I have this:
// Search criteria in the url
var ready = function(e){
$("#filterrific_filter").click(function(){
$.get($("#filterrific_filter").attr("action"), $("#filterrific_filter").serialize(), null, "script");
history.pushState(null, document.title, $("#filterrific_filter").attr("action") + "?" + $("#filterrific_filter").serialize());
e.preventDefault();
});
$(window).bind("popstate", function() {
$.getScript(location.href);
});
};
$(document).ready(ready);
$(document).on('page:load', ready);
The problem is: when a result is clicked on, and the users tries to go back to the search page again, they don't get back, they stay on the same page. The url changes though.
Here is a video to display the problem
And here is a link to the webpage, if you would like to test it yourself
Thanks in advance!

Try removing this whole section:
$(window).bind("popstate", function() {
$.getScript(location.href);
});
Since your apartments#show action (a guess, assuming you're using a RESTful design in your Rails backend) is a round-trip request (not AJAX, like your filter), and your query string URL will run the filterrific scripts correctly on a reload, you might as well let the back button work the default way.
Disclaimer: this is a shot in the dark without more context. If it doesn't work for you, and you provide more context, I'll happily revisit.

Related

Redirecting route - what is ember way?

In my app, I require to user to not use the back button of the browser on the last page. For that I find a way to replacing existing url with current page url. so user will stay with same page.
I am using this JS code :
init(){//writing at init
history.pushState(null, null, document.URL);
window.addEventListener('popstate', function () {
history.pushState(null, null, document.URL);
});
},
But what is the correct code of ember to replace the above code? what is the correct way to do?
thanks in advance.
You can prevent the user from transitioning to another route within your application by aborting any transition made from the willTransition hook of your last page's route. Add something like
actions: {
willTransition(transition) {
transition.abort();
}
}
to your last page's route

Browser network trace showing JSON post creating same file/link for every posting JQuery

I am using Json post method to get data from controller and display the data on Razor view page using dropdown list. When I am tracing browser network tab, I can see it is creating and keeping every post request and increasing the file size. I am new for JQuery. My question is, there are any way I can remove the previous post. Please see the image file below where I posted twice from dropdown list. I always want to keep the last post.
Please click to see the image
My JQuery code is -
$(document).ready(function ()
{
$('#ddl2').change(function (e)
{
e.preventDefault();
var data1 = {str_test: str_test };
var url = '#Url.Action("ddl_2")?id=' + id;
$.post(url, data1, function (data)
{
$('#nav_div').html(data);
});
});
});
Thanks
Either you're posting multiple time or you've called the same function with same selector each time. You could post your JS logic code here to debug correctly otherwise assumption answer aren't helpful.

Windows.history.back() + location.reload() jquery

I've a probleme in my code. The aim is to complete a simple form, then you click on a submit button. It do an Ajax resquest to go in the method. On success in the ajax request, i use windows.history.back() to go to the previous page ans here i want to refresh this page, to refresh values which are modificated by the form ! Have you an idea about that ?
$('#form_edit').submit(function (e)
{
e.preventDefault();
$.ajax({
url: $('#form_edit').attr('action'),
type: 'POST',
cache: false,
data: $(this).serialize(),
success: function (data) {
if (data === true) {
alert("Modification réussie !");
window.history.back();
location.reload(); <= on success i want to refresh previous page
}
else {
alert("Modification échouée !");
}
},
error: function ()
{
alert("Modification échouée !");
}
})
})
window.history.back(); Sometimes it's an issue with javascript compatibility with ajax call or design-related challenges.
I would use this below function for go back with the refresh.
function GoBackWithRefresh(event) {
if ('referrer' in document) {
window.location = document.referrer;
/* OR */
//location.replace(document.referrer);
} else {
window.history.back();
}
}
In your html, use:
BACK`
For more customization you can use history.js plugins.
This is the correct answer. It will refresh the previous page.
window.location=document.referrer;
It will have already gone back before it executes the reload.
You would be better off to replace:
window.history.back();
location.reload();
with:
window.location.replace("pagehere.html");
Try these ...
Option1
window.location=document.referrer;
Option2
window.location.reload(history.back());
You can't do window.history.back(); and location.reload(); in the same function.
window.history.back() breaks the javascript flow and redirects to previous page, location.reload() is never processed.
location.reload() has to be called on the page you redirect to when using window.history.back().
I would used an url to redirect instead of history.back, that gives you both a redirect and refresh.
I know this post is old but this can help.
window.location.replace(document.referrer);
After struggling with this for a few days, it turns out that you can't do a window.location.reload() after a window.history.go(-2), because the code stops running after the window.history.go(-2). Also the html spec basically views a history.go(-2) to the the same as hitting the back button and should retrieve the page as it was instead of as it now may be. There was some talk of setting caching headers in the webserver to turn off caching but I did not want to do this.
The solution for me was to use session storage to set a flag in the browser with sessionStorage.setItem('refresh', 'true'); Then in the "theme" or the next page that needs to be refreshed do:
if (sessionStorage.getItem("refresh") == "true") {
sessionStorage.removeItem("refresh"); window.location.reload()
}
So basically tell it to reload in the sessionStorage then check for that at the top of the page that needs to be reloaded.
Hope this helps someone with this bit of frustration.
I know this is pretty old but I thought my answer would help someone as most of codes here refreshed current page not previous one
so you can't get back to previous page and refresh it at same time as JS will run the code that takes you back and stops (will not run refresh page part) so I found a way to combine both functions
window.location.assign(window.history.back());
This basically will load a "new page" (so it will refresh it) but at same time it will load the previous page in browser history
window.history.back() does not support reload or refresh of the page. But you can use following if you are okay with an extra refresh
window.history.back()
window.location.reload()
However a real complete solution would be as follows:
I wrote a service to keep track of previous page and then navigate to that page with reload:true
Here is how i did it.
'use strict';
angular.module('tryme5App')
.factory('RouterTracker', function RouterTracker($rootScope) {
var routeHistory = [];
var service = {
getRouteHistory: getRouteHistory
};
$rootScope.$on('$stateChangeSuccess', function (ev, to, toParams, from, fromParams) {
routeHistory = [];
routeHistory.push({route: from, routeParams: fromParams});
});
function getRouteHistory() {
return routeHistory;
}
return service;
});
Make sure you have included this js file from you index.html
<script src="scripts/components/util/route.service.js"></script>
Now from you stateprovider or controller you can access this service and navigate
var routeHistory = RouterTracker.getRouteHistory();
console.log(routeHistory[0].route.name)
$state.go(routeHistory[0].route.name, null, { reload: true });
or alternatively even perform checks and conditional routing
var routeHistory = RouterTracker.getRouteHistory();
console.log(routeHistory[0].route.name)
if(routeHistory[0].route.name == 'seat') {
$state.go('seat', null, { reload: true });
} else {
window.history.back()
}
Make sure you have added RouterTracker as an argument in your function
in my case it was :
.state('seat.new', {
parent: 'seat',
url: '/new',
data: {
authorities: ['ROLE_USER'],
},
onEnter: ['$stateParams', '$state', '$uibModal', 'RouterTracker', function($stateParams, $state, $uibModal, RouterTracker) {
$uibModal.open({
//....Open dialog.....
}).result.then(function(result) {
var routeHistory = RouterTracker.getRouteHistory();
console.log(routeHistory[0].route.name)
$state.go(routeHistory[0].route.name, null, { reload: true });
}, function() {
$state.go('^');
})
Brandon Hoult answered of Dec 18, 2019 at 3:33
I didn't get at at first but YES, it works! via session variable flag, but I'll say it it backwards
Set this in the page you want to be refreshed if user goes back to it with history back or browser back.
if (sessionStorage.getItem("refresh") == "true") {
sessionStorage.removeItem("refresh"); window.location.reload()
}
Set this flag in the page you make changes like the shopping cart or the ajax mentioned that will change stuff, some setttings, classes, etc.
sessionStorage.setItem('refresh', 'true');
My case:
I hard code settings in a buy page while loading it, like prices and class of buy buttons: "add" or "in cart" icons. User adds an item to cart, then I add the product calling ajax and change that button's class to "in cart". If user wants to remove it from cart just clicks the cart icon and ajax again to remove it from cart and change class to "add".
Problem:
User goes to cart page itself, see the products and decide to go back and page show old buttons icons because is history (first loaded page, not changed one) so need to reload the show updated info.
Solution above does:
Buy page will reload if user goes to cart and back since cart page set a session variable "refresh" and buy page checks if "refresh" = true, set refresh it to false (so only cart page can set refresh to true and refresh the page.
Session variable "refresh" is a name so you can call it whatever else so you can use as many different flags as you want.
step 1: save the referrer URL in the local cache on load functions.
$(function () {
let refUrl = document.referrer;
let origin = location.origin;
if (refUrl.replace(origin, '') !== location.pathname) {
localStorage.setItem("history", refUrl.replace(origin, ''));
}
});
step 2: redirect the page to the referrer URL on link click.
$('body').on('click', '.lnkRurl', function () {
location.href = localStorage.getItem('history');
});

jQuery Ajax, prevent the refresh button when the ajax is in progress

Hi i have to perform perform like, when the ajax is in progress, then do not allow the user to do page refresh.
here is the code i have
$('#submit').click(function() {
$(function() {
$(".col1").mask("Generating csv...."); //This will generate a mark, Here i would like to prevent the user from doing any sort of operation.
var to = $('#filters_date_to').val();
var from = $('#filters_date_from').val();
$.ajax({
url:"../dailyTrade/createCsv?filters[date][to]="+to+"&filters[date][from]="+from,success:function(result){
if(result) {
$(".col1").unmask(); //Here we can unlock the user from using the refresh button.
window.location = '../dailyTrade/forceDownload?file='+result;
setTimeout('location.reload(true);',5000);
}
}
});
});
});
Any suggestions.
Best you can do is use onbeforeunload to present the user with a message saying that a request is in progress and asking them if they are sure they want to proceed.
e.g.
var req;
window.onbeforeunload = function() {
if(req) {
return 'Request in progress....are you sure you want to continue?';
}
};
//at some point in your code
req = //your request...
You cannot, in any way, prevent the user from leaving your page using JS or anything else.
I doubt if you should do that.
$(window).bind('beforeunload',function(){
return 'are you sure you want to leave?';
});
If you are talking about a refresh "html button" on your web page, that can easily be done. Just before you make your ajax call, disable your refresh button and on success/error function of the ajax call enable it.
Disable button
$("#refreshBtn").attr("disabled", "disabled");
Enable button
$("#refreshBtn").removeAttr("disabled");
You cannot do it just by inserting JavaScript code.
Only ways I can think of are:
Use synchronous ajax call, on that way browser should freeze (however it will notify user that script is taking too long to process and user will be able to stop execution)
Write browser plugin that will modify browser behavior (eg. prevent refreshing page for url that you preset)
Both ways are ugly and I wouldn't recommend doing it.
You should modify your script so it can resume execution if page has been refreshed (use HTML5 localStorage).
http://www.w3schools.com/html/html5_webstorage.asp
In your case, I would put in localStorage simple state (boolean) to check did ajax call happened or not. If it did happened, then just try calling again same url and you will get file name. But on server side (if you haven't done already) you should implement caching, so when same url is called twice, you don't need to make two separate files, it could be same file (server will be much lighter on hardware resources).

How to refresh a location w. javascript when the location has a target?

This is similar to, but not the same as How can I refresh a page with jQuery?:
I bring up a modal form that collects some stuff from the user and passes it off to the server via a $.ajax() call. The server sends back a path that should become the new window.location of the browser. So the ajax call wants to be something like:
$.ajax({
// stuff
success: function (destination) {
// other stuff
window.location = destination;
}),
// still more stuff
});
This works fine as long as destination is a pure path, like /some_path and if the browser is not currently on that page. However, if the path is the page that I'm currently on and also includes a target -- /some_path#some_target, I lose: the browser simply repositions the page at the specified target, but does not hit the server for a fresh view of the page, which I need (since the server has done some stuff during the ajax call).
So, maybe I just add a location.reload() after the window.location call? That would work when the code is running on the page to which it's being returned, I think. But if I'm on another page, I get hit by a race condition, where the reload is called before the browser has finished making the window.location change, and I get the old page reloaded, not the new destination.
Blurgh. Is there any way around this?
One approach would be to check if window.location.pathname (which is the path without # or ?) is the same as destination within your success callback:
success: function (destination) {
// other stuff
if (destination === window.location.pathname) {
window.location.reload(); // reload if we are on the same page
} else {
window.location = destination; // otherwise, navigate to "other" page
}
}),
window.location.reload() reloads the current page with POST data, while window.location.href=window.location.href does not include the POST data.

Categories

Resources