Javascript redirect concatenates url linstead of redirecting - javascript

I want to call a controller action whenever a value is updated from a textbox.
Note that this script sits inside the same view which will be returned from the Dispatch/Index controller action
I tried doing it like this:
<script>
$('#deliveryDate').change(function () {
var date = $('#deliveryDate').val();
var sDate = date.split('/');
location.href = 'dispatch/' + sDate[0] + sDate[1] + sDate[2];
});
</script>
And it works perfectly the first time the value changes (ie, the page redirects to /dispatch/12122016).
However, when I change the value again, it redirects to /dispatch/dispatch/13122016, so the value just keeps concatanating and this of course produces an error.
I tried chaging the redirect line to location.href = '#Url.Action("Index", "Dispatch")/' + sDate[0] + sDate[1] + sDate[2];, but now it just concatenates the new date on to the url instead of redirecting how I need it to... (ie, it navigates to /dispatch/12122016/13122016)
Is there ANY way of doing this without including the literal url path??
How can "clear" the current url before redirecting the action I need (which should just be dispatch/12122016 ?

Simply prepend a forward slash in the URL, this should always dictate that the url change is always bound to be absolute.
As a bonus: I also changed your date concatenation after /dispatch into a join.
$('#deliveryDate').change(function () {
var date = $('#deliveryDate').val();
location.href = '/dispatch/' + date.split('/').join('');
});

Try this by appending the forward slash. Because your concatenating the dispatch string on every redirect
<script>
$('#deliveryDate').change(function () {
var date = $('#deliveryDate').val();
var sDate = date.split('/');
Var URL = '/dispatch/' + sDate[0] + sDate[1] + sDate[2];
Window.location.href = URL
});
</script>

Related

Javascript window.location redirect with url rewriting, no querystring

I have endlessly googled for about an hour, so please forgive me if this has been asked before.
I am using pure Javascript and do not wish to use jQuery.
PREAMBLE
I have an HTML form with 3 select boxes that control a search of items. When one is updated, a simple function reads each of the values in the select boxes and produces a URL that matches our URL rewriting standard.
http://www.example.com/search/select1/data1/select2/data2/select3/data3/
This is then used in a
history.pushState
to update the browser's url address so a user can bookmark the page right away. This works fine.
PROBLEM
When the user presses the button of the form, what I want is the function to read all the select box values, generate the URL as before but also load this specific URL so that the underlying database code can return the results for that search on the page.
However, when I use
window.location.href
it loads the page, but also sends the querystring from the form submission. This mucks up the database code because, essentially, it's getting all the data twice.
EXAMPLE
I choose 'A' from select1, 'D' from select2 and 'E' from select3.
This results:
http://www.example.com/search/select1/A/select2/D/select3/E/?select1=A&select2=D&select3=E
SO...
Is it possible to generate the URL in the correct rewritten format, then load the page without the querystring?
JAVASCRIPT
function changepage(loadpage)
{
var theform
theform = document.getElementById("searchform");
var pageurl
pageurl = 'http://www.example.com/search/'
var select1 = theform.select1.value;
var select2 = theform.select2.value;
var select3 = theform.select3.value;
if(select1 != '')
{
pageurl = pageurl + 'select1/' + select1 + '/';
}
if(select2 != '')
{
pageurl = pageurl + 'select2/' + select2 + '/';
}
if(select3 != '')
{
pageurl = pageurl + 'select3/' + select3 + '/';
}
history.pushState('data', '', pageurl);
if(loadpage=='yes')
{
window.location.href = pageurl;
}
}
HTML
<form method="post" action="form.asp">
<select id="select1"><option>A</option><option>B</option></select>
<select id="select2"><option>C</option><option>D</option></select>
<select id="select3"><option>E</option><option>F</option></select>
<button onClick="changepage('yes');">
</form>

posting html content to controller method removes part of content

This is the js function:
var onContentChange = function () {
var content =
$("#blogpost-content").data("kendoEditor").value($("#value").val());
console.log(content);
$http.post("/Map/SaveBlogPostContent?destinationId=" +
$("#currentDestinationId").val() +
"&blogPostId=" + $("#currentBlogPost").val() + "&content=" + content)
.then(onSaveBlogPostContent, onError);
}
This method is triggered on change of a textarea.
When it hits the console.log it writes out the correct text that is currently in the textarea but when it posts the data to my controller method it only receives a bit of the content.
Why is this?
It's quite possible you have 'illegal characters' in your textarea, try to escape the content variable, change it like so:
var onContentChange = function () {
var content = $("#blogpost-content").data("kendoEditor").value($("#value").val());
console.log(content);
$http.post("/Map/SaveBlogPostContent?destinationId=" + encodeURIComponent($("#currentDestinationId").val()) + "&blogPostId=" + encodeURIComponent($("#currentBlogPost").val()) + "&content=" + encodeURIComponent(content))
.then(onSaveBlogPostContent, onError);
}
The encodeURIComponent() is the important part there.
Since this is a get and not a post, there are limits to the length of data you can send in the get request, it will depend by browser. you also want to make sure you dont have any characters that need to be escaped. eg. charters used in the url such as ? or & or /. you can escape these by using.
var contentToPass = encodeURIComponent(content);
see here encodeURIComponent
Try this:
var onContentChange = function () {
var content =
$("#blogpost-content").data("kendoEditor").value($("#value").val());
console.log(content);
$http.post("/Map/SaveBlogPostContent", {
destinationId: $("#currentDestinationId").val(),
blogPostId: $("#currentBlogPost").val(),
content: content
}).then(onSaveBlogPostContent, onError);
}

change part of the url text and reload page

Is there a way to make an a tag link that includes part of the current url?
I would use it to change language but stay on the current page!
If I am on:
www.mysite.com/contact
and I press on:
<a>FR</a>
the generated link would be:
www.mystie.com/fr/contact
Kind regards
Try this:
HTML:
FR
Now get the url from javascript
$("#myLink").click(function(e){
e.preventDefault();
var url = document.url; // get current page url
url = url.substr(0, url.indexOf('/')); // get substring from url
url += "/" + $(this).attr("href"); // add href of a tag to url
window.location.href = url; // locate the page to url
});
you can try with some like
function changeLng(lang) {
// remove language '/fr/' or '/es/' if exists
var path = window.location.pathname.replace(/\/[a-z]{2}/, '');
// reload the page same url with the lang prefix
window.location.href = '/' + lang + path;
}
the link can be
FR
ES
EN
this converts any url to lang specific, sample
/contact to /fr/contact
/about to /fr/about
update
for remove the lang part is simple
function removeLng() {
// remove language
var path = window.location.pathname.replace(/\/[a-z]{2}/, '');
window.location.href = path;
}

Loop on back button after re-direction with querystring

The problem:
I need to start with a URL with a query string containing a URL of a second page - http://www.firstURL.com/?http://www.secondURL.com. On the target page of the first URL, the query string is parsed to extract the second URL and the browser is re-directed to the second URL. This is done on $(document).ready so that it's automatic. This all works fine, but of course falls in a hole if the user hits the back button on the second URL. Here's the basic code:
$(document).ready(function() {
var s = location.search;
if(s != '') {
var split = s.split('?');
var loc = split[1].replace('?', '');
location.href = '' + loc + '';
} else {
//do something else on the target page..
}
});
I've tried creating a conditional case where, if the referrer is the 2nd URL (loc in the code above), the re-direction doesn't execute, but it seems that in the case of a re-direction, the back button doesn't return the referrer.
I have to do all this client side - I have no access to the server.
Is there some way to prevent the re-direction triggering on a back button click? Thanks.
Once you hit the second page, set a cookie in your browser indicating that the second page has been visited.
In the first page, before doing the redirection always check whether the cookie is not present.
Instructions on setting a cookie:
<script type="text/javascript">
document.cookie="secondpagevisited=43yj0u3jt;path=/"; //execute this line in the head of second page.
</script>
In first page, check for cookie presence:
<script type="text/javascript">
if(document.cookie.indexOf("secondpagevisited=43yj0u3jt")==-1){
/*do redirection here*/
}
</script>
EDIT: Assuming you control only the first page and not the second page, try this:
<script type="text/javascript">
if(document.cookie.indexOf("secondpagevisited=43yj0u3jt")==-1){
document.cookie="secondpagevisited=43yj0u3jt;path=/";
/*do redirection here*/
}
</script>
I gave Ashish the point for putting me on the right track, but this is my solution which goes one step further:
var s = location.search;
if(s != '') {
var split = s.split('?');
var loc = split[1].replace('?', '');
if (document.cookie.indexOf('redirected=' + loc + '') == -1) {
document.cookie = 'redirected=' + loc + '';
location.href = '' + loc + '';
} else {
var url = location.href.replace('' + s + '', '');
document.cookie = 'redirected=; expires=Thu, 01 Jan 1970 00:00:00 GMT';
history.pushState(null, null, '' + url + '');
}
If the cookie is there, the re-direction doesn't occur, the cookie is removed (in case the user returns to the site that had the original link and clicks it again), and the URL is tidied up by removing the query string.
Thanks for the guidance.

Append parameter in url without reloading page

I am using following code to append param to url. This is working fine but when parameter is appended in url, page is getting reloaded. I want to use this functionality without reloading the page .
function insertParam(key, value)
{
key = escape(key); value = escape(value);
var kvp = document.location.search.substr(1).split('&');
var i=kvp.length; var x; while(i--)
{
x = kvp[i].split('=');
if (x[0]==key)
{
x[1] = value;
kvp[i] = x.join('=');
alert('sdfadsf');
break;
}
}
if(i<0) {kvp[kvp.length] = [key,value].join('=');}
//this will reload the page, it's likely better to store this until finished
document.location.search = kvp.join('&');
//alert(document.location.href);
}
I want to add multiple params to url without reloading the page like:
txt1
txt2
txt3
link1
link2
link3
i want url : "..../search.php"
after click on txt2
i want url : "..../search.php#t_2"
after click on link2
i want url : "..../search.php#t_1&l_2"
You can only do this using history.pushState(state, title, url) which is an HTML5 feature.
There is a new feature that aims to replace the use of location.hash with a better solution: pushState.
window.history.pushState(data, "Title", "/new-url");
More information: http://badassjs.com/post/840846392/location-hash-is-dead-long-live-html5-pushstate

Categories

Resources