Query String Javascript - javascript

Using javascript, how do I add some data to the query string?
Basically I want to add the window.screen.height and window.screen.width info to the query string so that I can then email it with the other login info.
Alternatively, how would I populate a couple of hidden fields with the same data, a form is being submitted so I could pick it up from there?
Thanks, R.

I think that the latter option would be easier to implement. For example, if you have the hidden fields like this:
...
<input type="hidden" name="screenheight" id="screenheight" value="" />
<input type="hidden" name="screenwidth" id="screenwidth" value="" />
...
Then the JavaScript would be:
<script type="text/javascript">
document.getElementById('screenheight').value = window.screen.height;
document.getElementById('screenwidth').value = window.screen.width;
</script>

You can also use jquery.query.js to play with querystring.

for hidden fields, give each field an ID then do this
$("#fieldID").attr("value") = someValue;
UPDATE: Sorry, I saw Query and that made me think jQuery.

If you wanted to add it to the location in a library agnostic manner, you could do the following:
var query = window.location.search;
var sep = "?";
if (query) {
sep = "&";
}
window.location = window.location + sep + "h=" +
window.screen.height + "&w=" + window.screen.width;
This of course assumes that you don't have w or h parameters in the query string already.

Related

how to transfer values between html pages?

I'm opening new page from anothe like this:
var openedwidow = window.open(billhref, '', 'scrollbars=1,height='+Math.min(h, screen.availHeight)+',width='+Math.min(w, screen.availWidth)+',left='+Math.max(0, (screen.availWidth - w)/2)+',top='+Math.max(0, (screen.availHeight - h)/2));
the second html page looks like this:
<div class="row contractor_data__item">
<label for="code">Номер</label>
<input type="text" name="code" id="code" disabled/>
<input type="hidden" name="documentId" id="documentId">
<input type="hidden" name="actId" id="actId">
<input type="hidden" name="actCode" id="actCode">
</div>
on the page opening in the new window I have a few fields to fill. For example, I've filled "code" field on the first page and need to fill the "code" field in the page opened. How to do this?
the second part of question is that I've filled some fields on the page opened, like documentId and need to pass it to the first page I've called this one from on close, for example or on the field filled. How to perfrorm this?
In HTML5 you can use session to pass object from page to another:
// Save data to sessionStorage
sessionStorage.setItem('key', 'value');
// Get saved data from sessionStorage
var data = sessionStorage.getItem('key');
// Remove saved data from sessionStorage
sessionStorage.removeItem('key')
For further reference you can check here
Edit:
Sample Code:
Page1.html
<!DOCTYPE html>
<html>
<head>
<title>Page1</title>
<script type="text/javascript">
sessionStorage.setItem("name","ShishirMax");
var fName = sessionStorage.getItem("name");
console.log(fName);
function myFunction(){
window.open("page2.html");
}
</script>
</head>
<body>
This is Page 1
</br>
<button onclick="myFunction()">SendThis</button>
</body>
</html>
Page2.html
<!DOCTYPE html>
<html>
<head>
<title>Page 2</title>
</head>
<body>
This is Page 2</br>
<input type="text" name="txtName" id="txtName" value="">
<script type="text/javascript">
var fName = sessionStorage.getItem("name");
console.log(fName);
document.getElementById("txtName").value = fName;
</script>
</body>
</html>
Try the following code for the test purpose.
hi if you want transfer data in some page you can use localStorage our sessionStorage in js
difference between sessionStorage clear when you close browser and localstorage will be clear only if you ask it
go refer to documentation for sintax e.g :
you value is stak in 'data' variable in this e.g
var data;
sessionStorage.setItem('nameyourvar', data);
after you can take on other page with :
sessionStorage.getItem('nameyourvar')
Use a query string. That's what they're for. Dont' forget to wrap your values in encodeURIcomponent in case they contain any special characters.
window.open("somewhere.html?firstname="+encodeURIComponent(firstname)+"&lastname="+encodeURIComponent(lastname)+"");
In the new window you can get the values from the query string like this
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
var firstname = getParameterByName('firstname'); // "Bob"
var lastname = getParameterByName('lastname'); // "Dole"
Function is from here.
Since other people are mentioning localstorage, you should know that localstorage isn't supported in all browser. If you're interested in using something like that (you should really use query strings instead) you can check out this cross browser database Library I wrote.
Set your items to the database on the first page
jSQL.load(function(){
jSQL.createTable("UserData", [{FirstName: "Bob", LastName: "Dole"}]);
jSQL.persist(); // Save the data internally
});
Get your items from the second page
jSQL.load(function(){
var query = jSQL.query("SELECT * FROM `UserData`").execute();
var row = query.fetch("ASSOC");
var firstname = row.FirstName;
var lastname = row.LastName;
});
You can use GET parameters.
When you're opening second page, pass all the data you want to pass as GET parameters in the url, for example :
var billhref = "whatever.html?code=your_code&parameter2=parameter2_value" ;
var openedwidow = window.open(billhref, '', 'scrollbars=1,height='+Math.min(h, screen.availHeight)+',width='+Math.min(w, screen.availWidth)+',left='+Math.max(0, (screen.availWidth - w)/2)+',top='+Math.max(0, (screen.availHeight - h)/2));
Make a JS function to get parameters on the second page :
function getParams() {
var params = {},
pairs = document.URL.split('?')
.pop()
.split('&');
for (var i = 0, p; i < pairs.length; i++) {
p = pairs[i].split('=');
params[ p[0] ] = p[1];
}
return params;
}
Then use this function to get url parameters like this :
params = getParams();
for( var i in params ){
console.log( i + ' : ' + params[i] );
}
This will return output like :
code : your_code
parameter2 : parameter2_value
Using PHP will help you get around this problem with even shorter code
For example, in PHP, to get the parameters code, you'll just have to write :
$code = $_GET['code'];
And it will give you assign a variable named code the value you have passed in the url against code parameter( your_code in this example ).

Passing querystring from one page to another through javascript

I have two different pages. I want to send querystring from one to another. below is my sample code that i have tried
window.location.search = 'id='+hidposid.value;
window.location.href="editviewposition.aspx";
in another page i retrieve the value
cookie1 = HttpContext.Current.Request.QueryString("id") ' returns ""
<script type="text/javascript">
$(function () {
$("#btnQueryString").bind("click", function () {
var url = "Page2.htm?name=" + encodeURIComponent($("#txtName").val()) + "&technology=" + encodeURIComponent($("#ddlTechnolgy").val());
window.location.href = url;
});
});
</script>
<input type="button" id="btnQueryString" value="Send" />
Hope this will help u..
I think I'd rather do something like
window.location.href= 'editviewposition.aspx?id=' + hidposid.value;
Or is there a reason this is not possible?
Here you are passing query string not cookies
Get it like
window.location.search = '?id='+hidposid.value;
window.location.href="editviewposition.aspx";
and then in code behind
HttpContext.Current.Request.QueryString("id")

Prefix article keyword with date(Y-m-d)

In the CMS I am building, record names have to be unique (they are URL keywords). In order to achieve this with blog posts, I am attempting to prefix blog post titles with date("Y-m-d") in PHP.
I have a "title" input text field, in which the title is entered, a "keyword" text field which automatically "slugs" the title in order to turn it into a URL keyword.
I'm having trouble figuring out how to prefix the slugged title with the date.
Here's the code:
<input name="title" type="text" id="title" />
<input name="keyword" type="text" id="slug" />
<script type="text/javascript">
$(document).ready(function(){
$("#title").slug();
});
</script>
This part works. The title successfully turns into a keyword with dashes for spaces, eliminating special characters, etc.
I tried including the date by adding a hidden field with the date as the value and accessing its value with the getElementById function. I attempted to rework the javascript to concatenate the slugged title with the date:
<input type = "hidden" id = "postdate" value = "<?php echo date("Y-m-d"); ?>-" />
<script type="text/javascript">
$(document).ready(function(){
var getDate = document.getElementById('postdate');
var doSlug = $("#title").val();
var slugString = getDate + doSlug;
$("slugString").slug();
});
</script>
But I'm obviously not working properly with the javascript.
The output I'm after would be: "2013-10-09-title-of-this-blog-post"
Where am I going wrong?
Working Fiddle
I suggest you to do a little tweak to the plugin to be able to do what you want.
As you can see in the feedle above i add two new configuration parameters
prepend: null, // String to be prepended the sluged string
append: null // String to be appended the sluged string
and on the makeSlug function i just add this two conditionals
if(typeof settings.append === 'string')
slug = slug + '-' + settings.append;
if(typeof settings.prepend === 'string')
slug = settings.prepend + '-' + slug;
Now you can prepend or append a string to the slugfy version of your string
$("#title").slug({
prepend: '2010-10-13',
append: 'YAYY'
});
If you decide to use this approach, here is how to use with your html
$(document).ready(function(){
$("#title").slug({
prepend: $('#postdate').val()
});
});
How about:
$(document).ready(function(){
var getDate = $('#postdate').val(); // get the value of the postdate id, not the element.
var doSlug = $("#title").val();
var slugString = getDate + "-" + doSlug;
$('#title').val(slugString);
$('#title').slug(); // if needed.
});
The jQuery slug() function is changing the input value to be "slugged". You can't set it to "slugString", because that's a variable, not a dom element. If necessary, you can "reslug" the input value after setting it with val().
Edited to fix the getDate variable issue that #Oswaldo Acauan picked up

Form gives error when trying to append after question mark

I'm trying to send visitors to http://www.facebook.com/plugins/comments.php?href=http://google.com?c
Gives the error
The comments plugin requires an href parameter.
This part is rendered correctly: http://www.facebook.com/plugins/comments.php
but the stuff after the question mark fails to be included
<script>
function go(){
var uri = 'http://www.facebook.com/plugins/comments.php'
+ encodeURI('?href=http://google.com?c');
window.frames[0].document.body.innerHTML =
'<form target="_parent" method="get" action="'
+ uri
+ '"></form>';
window.frames[0].document.forms[0].submit();
}
</script>
<iframe onload="window.setTimeout('go()', 99)" src="about:blank" style="visibility:hidden"> </iframe>?
Change to:
var uri = 'http://www.facebook.com/plugins/comments.php?'
+ encodeURIComponent('href=http://google.com?c');
If you encode the first ? it no longer serves to separate the URL from its parameters.
Only the keys and value of the query should be encoded, not the ?,& or = as these are the characters that structure the query.
var uri = 'http://www.facebook.com/plugins/comments.php?href='
+ encodeURIComponent('http://google.com?c');

JQuery set cookies

How to save div title into cookies? And how to get this saved data, back?
<script type="text/javascript">
function setcookie(title, value, exp) {
var expdate = new Date();
expdate.setDate(expdate.getDate() + exp);
document.cookie = title+'='+value+';expires='+expdate.toGMTString()+';path=/';
}
</script>
<div title="1" onclick="setcookie();"></div>
See this question about jQuery and cookies. It will be easier to use a plug-in, like http://plugins.jquery.com/project/cookie.
Use following code to get the title of the div:
title = $("div").attr("title");
You may want to look into window.localStorage. It's very effective for what you are looking to do.
//Save the data
window.localStorage['mydiv'] = $('div').attr('title');
//Retrieve the data
$('div').attr('title', window.localStorage['mydiv']);

Categories