Accessing CGI values with Prototype - javascript

Anyone know the quickest way to grab the value of a CGI variable in the current URL using Prototype? So if I get redirected to a page with the following URL:
http://mysite.com/content?x=foobar
I am interested in retrieving the value of "x" (should be "foobar") in a function called on page load like this:
Event.observe(window, "load", my_fxn ());
Thanks

You may want to look at the parseQuery method. This should do all the splitting you'd expect on a standard querystring such as document.location.search
http://api.prototypejs.org/language/string.html#parsequery-instance_method
For example:
document.location.search.parseQuery()["x"];
Will be undefined if it's not present, and should be the value otherwise.

I couldn't find any shortcuts here, so in the end I just parsed the URL with js like so:
function my_fxn () {
var varsFromUrl = document.location.search;
// get rid of first char '?'
varsFromUrl = varsFromUrl.substring(1);
var pairsArray = varsFromUrl.split("&");
for (i = 0; i < pairsArray.length; i++) {
var pair = pairsArray[i].split("=");
if (pair[0] == "x")
alert(pair[1] + ' is what I want.');
}
}

Related

how to get single value by cookie in java script

java script code is store cookie
document.cookie = 'CookieName='+'grid';
i want to get CookieName value grid i haveto store many cookie but i get this one this cookie store at the first index in cookie
$( document ).ready(function() {
var CookieName=document.cookie;
if(CookieName =='grid')
{
$('#tab_b').hide();
$('#tab_a').show();
}
else {
$('#tab_a').hide();
$('#tab_b').show();
}
});
how to get CookieName value
I got the impression that you found the answer by Jay Blanchard too long, so I'll provide a shorter alternative. But first let me say something else. As a comment to Jay Blanchard's answer, you wrote:
thanks bro i have got it and very simple and short function check it var allcookies = document.cookie; cookiearray = allcookies.split(';'); name = cookiearray[0].split('=')[0]; value = cookiearray[0].split('=')[1];
However, I highly recommend you rethink that as this assumes CookieName is always the first cookie. (Someone might say "but I will somehow make sure it always is", but the point is, this is key/value, not array, so the approach is conceptually wrong and confusing, or as they say, bad practice).
Now, for the code:
var cookieValue = document.cookie.replace(/(?:(?:^|.*;\s*)CookieName\s*\=\s*([^;]*).*$)|^.*$/, "$1");
This is something I have blantantly stolen from the MDN page on cookies which I highly recommend if you want to learn more about cookies.
I have written a small function (I could probably make this much more efficient, but I have used it for a long time) which should work for you:
function getCookieAttr(attribute) {
var attr = attribute + "="; // create an attribute string
var parts = document.cookie.split(';'); // split the cookie into parts
for(var i = 0; i <parts.length; i++) { // loop through the parts for each item
var item = parts[i];
while (item.charAt(0)==' ') { // account for spaces in the cookie
item = item.substring(1); // set the item
}
if (item.indexOf(attr) == 0) { // if the item matches the attribute
return item.substring(attr.length,item.length); // return the value
}
}
return "";
}
To use the function pass the attribute name:
document.cookie = "CookieName=grid";
console.log(getCookieAttr('CookieName'));

Google Script to see if text contains a value

I have a google form that when the user submits it will trigger my function to run which is creating a summary of what they submitted as a Google Doc. I know it can automatically send an email but I need it formatted in a way that my user can edit it later.
There are some check boxes on the form -- but the getResponse() is only populated with the items checked and I need it to show all possible choices. Then I will indicate somehow what was checked.
I can't find a way to see if a text contains a value.
Like in Java with a String, I could do either .contains("9th") or .indexOf("9th") >=0 and then I would know that the String contains 9th. How can I do this with google scripts? Looked all through documentation and I feel like it must be the easiest thing ever.
var grade = itemResponse.getResponse();
Need to see if grade contains 9th.
Google Apps Script is javascript, you can use all the string methods...
var grade = itemResponse.getResponse();
if(grade.indexOf("9th")>-1){do something }
You can find doc on many sites, this one for example.
Update 2020:
You can now use Modern ECMAScript syntax thanks to V8 Runtime.
You can use includes():
var grade = itemResponse.getResponse();
if(grade.includes("9th")){do something}
I had to add a .toString to the item in the values array. Without it, it would only match if the entire cell body matched the searchTerm.
function foo() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getSheetByName('spreadsheet-name');
var r = s.getRange('A:A');
var v = r.getValues();
var searchTerm = 'needle';
for(var i=v.length-1;i>=0;i--) {
if(v[0,i].toString().indexOf(searchTerm) > -1) {
// do something
}
}
};
I used the Google Apps Script method indexOf() and its results were wrong. So I wrote the small function Myindexof(), instead of indexOf:
function Myindexof(s,text)
{
var lengths = s.length;
var lengtht = text.length;
for (var i = 0;i < lengths - lengtht + 1;i++)
{
if (s.substring(i,lengtht + i) == text)
return i;
}
return -1;
}
var s = 'Hello!';
var text = 'llo';
if (Myindexof(s,text) > -1)
Logger.log('yes');
else
Logger.log('no');

passing alphanumeric value in querystring in url does not work in flash

I am having a flash application where I want to send paramters to it via the javascript from a defaul.aspx page.
I have a paramter called Id where it can accept alphanumerica values.
the query string in the url works fine if I enter just numbers for the Id, and takes me to the specific page relted to that id , but if I enter a combination of numbers and characters like 001A , it does not work.
this is the code I used
<script type="text/javascript">
function getQueryVariable(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0; i<vars.length; i++)
{
var pair = vars[i].split("=");
if (pair[0] == variable)
return (pair[1]);
}
}
</script>
and then later I assigned the first page of flash application to it.
flashvars.StartPage = getQueryVariable("Id");
and then passed the flashvars into swfobject.embedSWF
I also don't want to change anything in my mxml files in flash side
I appreciate if anyone could help me what the problem is
thanks
No you don't need to use JavaScript to process the value from querystring and then to send to flash.
Just make use of ExternalInterface.call function to grab variables (In this case : GET ) from URL.
Here's the code how it works. Add this code inside your MXML.
var pageURL : String = ExternalInterface.call("window.location.href.toString");
var paramPairs : Array = pageURL.split("?")[1].split("&");
for each (var pair : String in paramPairs)
{
var pairHolderx:Array = pair.split("=");
arrVals[counter]=pairHolderx[1];
counter++;
}
So if your URL is like http://www.stackoverflow.com/page.aspx?id=230A78&id2=8934
The arrVals[0] contains 230A78 and arrVals[1] contains 8934

Get Query String with Dojo

Users will be hitting up against a URL that contains a query string called inquirytype. For a number of reasons, I need to read in this query string with javascript (Dojo) and save its value to a variable. I've done a fair amount of research trying to find how to do this, and I've discovered a few possibilities, but none of them seem to actually read in a query string that isn't hard-coded somewhere in the script.
You can access parameters from the url using location.search without Dojo Can a javascript attribute value be determined by a manual url parameter?
function getUrlParams() {
var paramMap = {};
if (location.search.length == 0) {
return paramMap;
}
var parts = location.search.substring(1).split("&");
for (var i = 0; i < parts.length; i ++) {
var component = parts[i].split("=");
paramMap [decodeURIComponent(component[0])] = decodeURIComponent(component[1]);
}
return paramMap;
}
Then you could do the following to extract id from the url /hello.php?id=5&name=value
var params = getUrlParams();
var id = params['id']; // or params.id
Dojo provides http://dojotoolkit.org/reference-guide/dojo/queryToObject.html which is a bit smarter than my simple implementation and creates arrays out of duplicated keys.
var uri = "http://some.server.org/somecontext/?foo=bar&foo=bar2&bit=byte";
var query = uri.substring(uri.indexOf("?") + 1, uri.length);
var queryObject = dojo.queryToObject(query);
//The structure of queryObject will be:
// {
// foo: ["bar", "bar2],
// bit: "byte"
// }
In new dojo it's accessed with io-query:
require([
"dojo/io-query",
], function (ioQuery) {
GET = ioQuery.queryToObject(decodeURIComponent(dojo.doc.location.search.slice(1)));
console.log(GET.id);
});
Since dojo 0.9, there is a better option, queryToObject.
dojo.queryToObject(query)
See this similar question with what I think is a cleaner answer.

Getting URL in Javascript

Ok, I'm new to JavaScript and need some help here. Working on forward/backward buttons on a page. Essentially, the url looks like this http://webaddress.com/details?id=27
So, my two functions are meant to extract the url and forward to the same page decrementing or incrementing the details id as necessary when one of the buttons is clicked. For example when someone clicks on the next button, id=28 is shown; and if previous is clicked, id=26 is shown.
I think it's something like substring, I've seen it done somewhere before, but not sure how's done.
I need idea on how to approach it.
Any help will be appreciated.
Update: I was using #gion_13's code below, but looks like I'm missin something. It doesn't seem to work. Any other help will be appreciated.
You can use location.href to get or set the URL.
http://developer.mozilla.org/en/window.location
Use exec to extract the identifier.
extracted_id = /id=([0-9]+)$/.exec(location.href)[1]
http://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp/exec
Read the url as var url = document.location.href
Use regEx or indexOf "=" or document.location.search to find current page no
Parse as int and +/- page number
rebuild the the url
document.location.replace(newurl)
function parseUrl(){
if(location.href.indexOf('?') == -1)
return null;
var aux = location.href.split('?');
var result = {
'href' : aux[0],
'params' : {}
};
var p = aux[1].split('&');
for(var i=0,l=p.length;i++)
{
var kv = p[i].split('=');
params[kv[0]] = kv[1];
}
return result;
}
function reconstructUrl(obj){
if(!obj)
return location;
var url = obj.href + '?';
for(var i in obj.params)
url += i + '=' + obj.params[i] + '&';
return encodeURI(url);
}
function getNextUrl(){
var urlObj = parseUrl();
urlObj.id++;
return reconstructUrl(urlObj);
}
function getPrevUrl(){
var urlObj = parseUrl();
urlObj.id--;
return reconstructUrl(urlObj);
}
The window.location object has the URL info you need. You can parse it using a regex. Here's some references:
https://developer.mozilla.org/en/window.location
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp
To access the URL of the page, use document.URL, for example:
document.write(document.URL);
You can then modify the URL and open the new URL.
For lots of hints and tips, See JavaScript HTML DOM Examples.
You can do that without Javascript if you want. I think it's more efficient with PHP, because it will work even if some user has Javascript disabled.
You can try get the id like this:
<?php $my_id = $_GET['id']; ?>

Categories