Append parameter in url without reloading page - javascript

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

Related

Javascript redirect concatenates url linstead of redirecting

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>

is it possible to use javascript var i= [["j.php?i="+input]]; to send to php?

I am new and just doing practices i just did:
var i= [["j.php?i=1"]]; and it sent value to php and prints but when i want some input from user it does nothing. For example:
file j.js
var input = "hello";
var send= [["j.php?i="+input]];
and in j.php
<?php
$e=$_GET['i'];
echo $e;
?>
Any idea or i am totally wrong? I am trying to have some variation. And i really did with window.location.href. But I just want to know how to do in this way var send= [[]]. Thanks
Edit:
your question is not very clear, maybe try this:
var input = "hello";
var url = "/j.php?i=" + input;
var send = [[url]];
But, it's not clear to me what you want to do with your send variable...
Original
You have to send the data to the server either using a a tag (GET method), a form (POST method) or an Ajax request (any Http verb):
<!-- Here you give a unique id to your link -->
<a id="link" href="">your link</a>
<script>
var i = "Hello";
// wait for page to be loaded
document.addEventListener("DOMContentLoaded", function(event) {
// change the href attribute of the link with the id equal to 'link'
// with whatever data contained in the i variable
// this is done after the page is loaded
document.getElementById("link").href = "/j.php?i=" + i;
});
</script>
Then, when you just click the link, it will send the variable named i containgin the value Hello to your php page.
You could also do it in this way:
<a id="link2">your link</a>
<script>
var i = "HELLO";
// wait for page to be loaded
document.addEventListener("DOMContentLoaded", function(event) {
// here we are telling javascript to change the url
// in the browser when the user clicks the link
document.getElementById('link2').onclick = function() {
window.location = '/j.php?i=' + i
}
});
</script>

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>

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.

Getting a form's submit URL as a relative url?

Let's say I have a form located at:
http://www.mysite.com/some/place/some/where/index.php
And I have this form:
<form action="submit.php"> ... </form>
If I do this:
$("form").attr("action");
I will get:
submit.php
What is a foolproof way to get the action from the form, so that it includes the entire URL:
http://www.mysite.com/some/place/some/where/submit.php
?
Try
$("form").prop("action");
or (assuming your form is in the same folder as the page and the page URL ends with /something)
var loc = location.href;
var page = loc.substring(0,loc.lastIndexOf("/")+1)+
$("form").attr("action");
Handle query strings and hashes especially for Quentin:
Live Demo
var loc = location.origin + location.pathname;
var action = $("form").attr("action").split("/").pop();
var page = loc.substring(0,loc.lastIndexOf("/"))+"/"+action;
var el = document.createElement('a');
el.href = $("form").prop("action");
alert(el.href);
Chrome adjusts the href to give the absolute url, not sure with other browsers

Categories

Resources