Redirect to Page.aspx redirects to undefined - javascript

Simple JavaScript redirect window.location.href = https://example.org/Page.aspx?q=123 to .aspx resource causes page to navigate to https://example.org/undefined?q=123.
Manual navigation to the address works as expected.
I am not familiar with ASP.NET much so I was wondering if that's a common problem or is it only specific to the project that I am working on?
If we assume that some script modifies the URL later down the line, is there any way to stop that?
e.preventDefault()? Or stopImmediatePropagation()?
Thanks!
UPDATE:
Used code snippet:
$('body').on('keydown', selectorSearchBoxInput, function (e) {
var inputValue = $(this).val();
if (e.keyCode == 13 && !!inputValue) {
var newHref = 'https://example.org/Category/SubCategory/Page.aspx?q=' + encodeURIComponent(inputValue.trim());
window.location.href = newHref;
}
});

Related

location.replace() and move to a new page when data is returned

I need to move to another page after some data is returned from a $.post() ?
verifystudent.html:
$.post('students/verify.php',
function(results){
preventdefault();
location.replace("verifystudent.html");
window.location.href = "completed/student_result.html;
}
Basically when the data is received to the verifystudent.html it should move to student_result.html and when the browser back button is clicked it should avoid going to verifystudent.html. How can I do this?
Try this script it prevents browser's back button so use it in verifystudent.html
<script type = "text/javascript" >
history.pushState(null, null, 'pagename');
window.addEventListener('popstate', function(event) {
history.pushState(null, null, 'pagename');
});
</script>
Hope this helps.
Use SessionStorage to save the state of your application. You can create a key to mark that a student is verified.
Check for this key when the verification page loads and use location.replace to change the URL if the student is already verified.
Also read this article about preventing users from going to the previous page.
For your second question "and when the browser back is clicked it should avoid going to verifystudent.html"
I was searching for the same question and I found following code on a site. Thought to share it here:
function noBack()
{
window.history.forward()
}
noBack();
window.onload = noBack;
window.onpageshow = function(evt){ if(evt.persisted) noBack(); }
window.onunload = function(){ void(0); }
However as noted by number of developers, this is never a good practice and should be avoided for all reasons.
You could use the JQuery navigation event on verifystudent.html to send the user to the desired page
$(window).on("navigate", function (event, data) {
var direction = data.state.direction;
if (direction == 'back') {
window.location.href = "completed/student_result.html;
}
}

What's the best way to force a hashchange?

My website uses hashchange-triggered AJAX (to make it more bookmark-friendly). The problem I am having is that when I click "submit" in a form, all the form data that is serialize()'d to be sent via $.post() gets lost. I know this because I get the "Flag 1" alert after I click submit, and various other tests (alerting, echoing, etc.) show this to be true.
Here's my current code:
$(document).ready(function() {
var data = '';
var hash = '';
newPage();
alert('Flag 1');
$(window).bind('hashchange', function() {
hash = window.location.hash;
if (hash == '') {
path = window.location.pathname;
hash = '#' + path.replace(/^\/+/, '');
}
data += '&func=' + hash;
var xhr = $.post(hash, data, function(result) {
$("maincontent").html(result);
})
.done(newPage);
});
// Initialize vars and handle new form elements
function newPage() {
data = '';
$('form').submit(function() {
data = $(this).serialize();
// Flag 2 - What do I do here?
});
}
// Load ajax content on first run of document
if ($('#maincontent').html() == '')
$(window).trigger('hashchange');
});
What I am trying to do is manually fire a hashchange event while also changing the URL. The trouble is that if I just set window.location.hash = $(this).attr('action'); then return false; where the "Flag 2" comment is, then I wind up getting unwanted trash in the URL, possibly due to the hashmark being encoded for a URL (...%23, etc).
I am wondering what the best way to set the hash is, and whether there is a simpler way to do what I am trying to do to begin with.
(I'm also open to comments suggesting alternate approaches for the style of navigation I am trying to achieve)
Well, I understand there are lots of errors doing this. But we have alternative options for this you will surely like:
jQuery History Plugin : http://plugins.jquery.com/history/ (Demo: http://4nf.org/)
History JS: https://github.com/browserstate/history.js/
But I would recommend HTML5 history.pushState if you are willing to avoid older browser support. (Demo: https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history)
Good luck!!

Exit Popup Redirect With a Exception

I also dont like exit popups but i want to integrate if for a comming festival day so want to thanks my visitors and gave them some thing special.
I am this code below for redirect on exit.
var exitPop = false;
var nonFire = false;
window.onbeforeunload = function () {
if(!exitPop){
exitPop=true;
return 'Happy Festival Day!';
}
};
setInterval(function(){
if(exitPop && !nonFire){
nonFire = true;
window.location.href = 'http://google.com';
}
}, 200);
I am using this code below its basically redirect on doing a comment
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.Event.subscribe('comment.create',
function (response) {
window.location = "http://domain.com";
});
FB.Event.subscribe('comments.remove',
function (response) {
window.location = "http://domain.com";
});
};
(function() {
var e = document.createElement('script');
e.async = true;
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
//]]>
</script>
and i dont want to show exit redirect to the my visitors who comment because its annoy my visitors i want that code execute only on clicking exit. so what code i should include which create exception of comment redirect and should not show popup to commenter
A popup window will only not be blocked if some link opens it. So if you are trying to load something on exit it won't work.
This is a working example: http://swip.codylindley.com/popupWindowDemo.html using a little library in jquery someone wrote. You can check out the source.
Basically, if the popup window opens onclick you should be fine, but in any other cases it will be blocked.
I am not sure how certain companies get away with it, but any sort of hacks eventually get plugged. One way I attempted to do it was to trigger an onclick action on a link and even that didn't work. So it is fairly fool proof.
You could do this by setting a cookie in javascript. You could do this with straight javascript but the code is shorter with the jquery.cookies plugin so ill demonstrate that method.
In your comment.create function, set a cookie to show that this user has made a comment:
FB.Event.subscribe('comment.create',
function (response) {
$.cookie('has_commented', 'true');
window.location = "http://domain.com";
});
Then check the cookie value on your exit function:
if($.cookie('has_commented') == true) {
return 'Happy Festival Day!';
}
Jquery Cookies plugin here: https://github.com/carhartl/jquery-cookie/blob/master/README.md
or if you want to do the same thing with straight javascript - same concept - but a bit messier.. info here: http://www.w3schools.com/js/js_cookies.asp

Window.Location Not Working In IE?

I have been trying to figure this out all afternoon, but have given up and now turning to you clever people to help :)
I have the following Jquery/Javascript function, which is working fine in Chrome - BUT in IE nothing happens?
$(".btnsubmitpost").click(function () {
var topicid = $(this).attr('rel');
var sbody = tinyMCE.get('txtPost').getContent();
$('.topicpostlistnewpost').remove();
$('.postsuccess').show();
$.post("/myurl/" + topicid + ".aspx",
{ "postcontent": sbody },
function (data) {
var returnUrl = $("value", data).text();
window.location.href = returnUrl;
return false;
});
return false;
});
I have tried window.location, window.location.href both with full urls and absolute Urls but IE just doesn't like it? Any ideas?
The function just gets a Url back from a post, and is supposed to redirect the user to the Url. But like I say, works in Chrome fine just not in IE (Tried IE8 and IE9)
Just for anyone having the same issue, the problem was because the window.location was inside the Ajax post method.
Just replace the window.location with a function() that then calls the window.location or do it after the Ajax call completely.

Go up one "folder" or segment in jQuery / Javascript

If I'm, for example, on this page
www.example.com/admin/bridge/boilerplate
What is the best way (Using plain javascript, or jQuery (Without loading another plugin) to go up one level, e.g.
www.example.com/admin/bridge
At the moment we are using
window.history.go(-1);
which interferes with submitted forms, etc.
This is used normally on a function like this:
$("button.cancel").bind("click", function( e ){
window.history.go(-1);
e.preventDefault();
});
Simple:
var url = window.location.href;
if (url.substr(-1) == '/') url = url.substr(0, url.length - 2);
url = url.split('/');
url.pop();
window.location = url.join('/');
var i = window.location.href.lastIndexOf("/");
window.location = window.location.href.substr(0,i)
thanks, but this edited:
$("#back a").click(function() {
var url = window.location.href;
if (url.substr(-1) == '/') url = url.substr(0, url.length - 2);
url = url.split('/');
url.pop();
window.location = url.join('/');
});
window.history is actually manipulating what is in your browser history, it is what the back/forward buttons in the browser use.
So, if the only way to get to the directory you are in is to navigate to it by digging down through the parent directories, this would work. However, that is never the only way to get to a page. Users are always able to bookmark the page.

Categories