How to assign $_GET value to a variable using pure JavaScript - javascript

Hi guys can How to assign $_GET value to a variable using pure JavaScript I have HTML structure not php

You could do something like this
function getGETParameter(key) {
var params = window.location.search.slice(1).split('&'),
i = params.length;
key += '=';
while (i-- > 0) {
if (params[i].lastIndexOf(key, 0) === 0)
return params[i].slice(key.length);
}
return false;
}
You may also want to consider if you want to use decodeURIComponent on these values as they may be URI encoded
If you want to also permit keys to be URI encoded then this method starts to have issues and you would have to create an Object mapping, which would look something like this
function getGETParameter(key) {
var params = window.location.search.slice(1).split('&'),
i = params.length,
j,
o = Object.create(null);
for (i = 0; i < params.length; ++i) {
j = params[i].indexOf('=');
if (j === -1) // how do you want to treat found but no value?
o[decodeURIComponent(params[i])] = null;
else
o[decodeURIComponent(params[i].slice(0, j))] = decodeURIComponent(params[i].slice(j + 1));
}
if (key in o) return o[key];
return false; // how do you wan to treat not found?
}
You could also create and cache this Object in advance instead of generating it for each invocation

combine the php code and javascript code !
var x=<?php echo $_GET['whatever'];?>;
so first the php code is being executed server-side and then it's result in html is assigned to a variable in javascript ...

Related

How to parse read json elements with jquery

I have to create cart system in my mobile application, i want to store the id and the quantity of products, the id should be the key of my array (for modifying product quantity) , tried to use object instead of array but i get error: undefined is not a function when i try to read my json variable
by JSON.stringify(cart)
My cart code is like this
var cart = [];
var produit = {};
produit['qte'] = $('.'+id_prd).text();
produit['id_produit'] = id_prd;
cart[id_prd] = produit;
window.sessionStorage["cart1"]= JSON.stringify(cart);
return me
{"7":{"qte":"1","id_produit":7},"8":{"qte":"1","id_produit":8}}
when I tried to parse the json string with
var parsed = $.parseJSON(window.sessionStorage["cart1"]);
i get the error 'undefined is not a function'
when triying to read the json with
var i=0;
for (k in parsed) {
var k_data = parsed[k];
k_data.forEach(function(entry) {
alert(entry);
ch+=entry.id_produit;
if(i<parsed.length-1)
ch+= ',';
if(i==parsed.length-1)
ch+=')';
i++;
});
}
Can you clarify me the error cause, and if there's a solution to better read the json
The problem is that you are using k_data.forEach(function(entry) but forEach is for Arrays, and k_data is just a simple javascript object.
Try changing:
k_data.forEach(function(entry){
to this:
$(k_data).each(function(entry){
Even more, if the JSON is always in the same structure you posted, I think the each function is not necessary, maybe this is the way you are looking for:
var i=0;
var ch = "(";
for (k in parsed) {
var k_data = parsed[k];
alert(k_data);
ch+=k_data.id_produit;
ch+= ',';
i++;
}
ch = ch.substring(0, ch.length - 1) + ")";
You shouldn't need jQuery for this. The same JSON object you used to stringify has a parse function:
var parsed = JSON.parse(window.sessionStorage["cart1"]);
If that still breaks, there's probably something wrong with another undefined object.
You can try something like this:
<script type="text/javascript">
var finalArr = new Array();
var dataArr = new Array();
dataArr = window.sessionStorage["cart1"];
if (JSON.parse(dataArr).length > 0) {
for (var i = 0; i < JSON.parse(dataArr).length; i++) {
finalArr.push((JSON.parse(dataArr))[i]);
}
}
</script>

Difficulty writing a function to extract URL from array

I'm trying to extract a URL from an array using JS but my code doesn't seem to be returning anything.
Would appreciate any help!
var pages = [
"www.facebook.com|Facebook",
"www.twitter.com|Twitter",
"www.google.co.uk|Google"
];
function url1_m1(pages, pattern) {
var URL = '' // variable ready to accept URL
for (var i = 0; i < pages[i].length; i++) {
// for each character in the chosen page
if (pages[i].substr(i, 4) == "www.") {
// check to see if a URL is there
while (pages[i].substr(i, 1) != "|") {
// if so then lets assemble the URL up to the colon
URL = URL + pages[i].substr(i, 1);
i++;
}
}
}
return (URL);
// let the user know the result
}
alert(url1_m1(pages, "twitter")); // should return www.twitter.com
In your case you can use this:
var page = "www.facebook.com|Facebook";
alert(page.match(/^[^|]+/)[0]);
You can see this here
It's just example of usage RegExp above. Full your code is:
var pages = [
"www.facebook.com|Facebook",
"www.twitter.com|Twitter",
"www.google.co.uk|Google"
];
var parseUrl = function(url){
return url.match(/^(www\.[^|]+)+/)[0];
};
var getUrl = function(param){
param = param.toLowerCase();
var page = _(pages).detect(function(page){
return page.toLowerCase().search(param)+1 !== 0;
});
return parseUrl(page);
};
alert(getUrl('twitter'));
You can test it here
In my code I have used Underscore library. You can replace it by standard for or while loops for find some array item.
And of course improve my code by some validations - for example, for undefined value, or if values in array are incorrect or something else.
Good luck!
Im not sure exactly what you are trying to do, but you could use split() function
var pair = pages[i].split("|");
var url = pair[0], title=pair[1];

Need help traversing JSON object in Javascript

I have code that calls a WCF service and returns a JSON string to the client. Below is the javascript function I am trying to use to parse the JSON but can not figure out how to traverse it.
Here is the function
loadDropDown: function(result, ddl, defaultItem) {
var _data = result.get_object();
//Sys.Serialization.JavaScriptSerializer.deserialize(result, true);
this.clearDropDown(ddl);
this.createOption(ddl, defaultItem, '');
for (var i = 0; i < _data.length; i++) {
var _item = _data[i];
var _option = this.createOption(ddl, _item.Text, _item.Value);
}
ddl.disabled = false;
}
Here is the JSON
{
"d": "[{\"Attributes\":{\"Keys\":[],\"Count\":0,\"CssStyle\":{\"Keys\":[],\"Count\":0,\"Value\":null}},\"Enabled\":true,\"Selected\":false,\"Text\":\"Lexus\",\"Value\":\"Lexus\"},{\"Attributes\":{\"Keys\":[],\"Count\":0,\"CssStyle\":{\"Keys\":[],\"Count\":0,\"Value\":null}},\"Enabled\":true,\"Selected\":false,\"Text\":\"Acura\",\"Value\":\"Acura\"}]"
}
any suggestions on why this is not working? Note: I am not using jquery in the solution.
You shouldn't be generating that json. Instead, you should be outputting
{
"d": [{"Attributes":{"Keys":[],"Count":0,"CssStyle":{"Keys":[],"Count":0,"Value":null}},"Enabled":true,"Selected":false,"Text":"Lexus","Value":"Lexus"},{"Attributes":{"Keys":[],"Count":0,"CssStyle":{"Keys":[],"Count":0,"Value":null}},"Enabled":true,"Selected":false,"Text":"Acura","Value":"Acura"}]
}
(quotes removed from "d" value)
There's no reason to convert json to a string before putting it in a json object! Just put the json straight in.
You should be able to just eval() the object (or use JSON parsing from Crockford) and access your properties in regular object notation. You may need to unescape your identifiers first, though.
You need to do eval(_data) before you use it as a javascript array.
for ex:
var _rawdata = result.get_object();
var _data = eval(_rawdata);
//Sys.Serialization.JavaScriptSerializer.deserialize(result, true);
this.clearDropDown(ddl);
this.createOption(ddl, defaultItem, '');
for (var i = 0; i < _data.length; i++) {
var _item = _data[i];
var _option = this.createOption(ddl, _item.Text, _item.Value);
}
ddl.disabled = false;

How to read get request using Javascript?

So I have html page called A.html it was called like this from B.html : A.html?varString="bla-bla-bla" Is it correct for sending args to JS? How to parse args from JS?
(not using any frameworks like Jquery, working in IE6, FireFox 3)
Here is a function to parse the query string. Pass it the parameter name and it returns the value.
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];
}
}
return -1; //not found
}
Use location.search:
alert(location.search); // will display everything from the ? onwards
You probably want to separate the different variables from the query string so that you can access them by name:
var request = {};
var pairs = location.search.substring(1).split('&');
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split('=');
request[pair[0]] = pair[1];
}
Then you can access it like request['varString'] and that will give you "bla-bla-bla".
Mostly you'd like to handle the parameters passed to your page in the server side, but if you got your reasons why to do it client-side, here's a small script i found:
function gup( name )
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
i didn't test it, but i'm pretty sure it'll to the job.
just use it like: gup('parameter') and it'll return the parameter value for you.
To parse the query string through JS, you can view use something like
function getQueryValue(param) {
var queryStringArray = querystring && querystring.substring(1).split("&");
for (var i=0, length = queryStringArray.length; i < length; i++) {
var token = queryStringArray[i],
firstPart = token && token.substring(0, token.indexOf("="));
if (firstPart === param ) {
return token.substring(token.indexOf("=") + 1, token.length);
}
}
}
E.g. Given a URL "http://domain.com.au?aaa=bbb , you can call this fn as getQeuryValue("aaa") and you'll get "bbb"
I uploaded this code on Gist (bit modified to be compliant with a module pattern).
Thanks to the new URLSearchParams interface, it becomes easier:
var url = new URL("https://example.org/?foo=bar&foo2=bar2");
var params = url.searchParams;
// Access to a variable
console.log(params.get("foo"));
// Loop over params
for (var key of params.keys()) {
console.log(params.get(key));
}
You should check Mozilla Developer Network for browser compatibility, since it's a new API.

how to get GET and POST variables with JQuery?

How do I simply get GET and POST values with JQuery?
What I want to do is something like this:
$('#container-1 > ul').tabs().tabs('select', $_GET('selectedTabIndex'));
For GET parameters, you can grab them from document.location.search:
var $_GET = {};
document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function () {
function decode(s) {
return decodeURIComponent(s.split("+").join(" "));
}
$_GET[decode(arguments[1])] = decode(arguments[2]);
});
document.write($_GET["test"]);
For POST parameters, you can serialize the $_POST object in JSON format into a <script> tag:
<script type="text/javascript">
var $_POST = <?php echo json_encode($_POST); ?>;
document.write($_POST["test"]);
</script>
While you're at it (doing things on server side), you might collect the GET parameters on PHP as well:
var $_GET = <?php echo json_encode($_GET); ?>;
Note: You'll need PHP version 5 or higher to use the built-in json_encode function.
Update: Here's a more generic implementation:
function getQueryParams(qs) {
qs = qs.split("+").join(" ");
var params = {},
tokens,
re = /[?&]?([^=]+)=([^&]*)/g;
while (tokens = re.exec(qs)) {
params[decodeURIComponent(tokens[1])]
= decodeURIComponent(tokens[2]);
}
return params;
}
var $_GET = getQueryParams(document.location.search);
There's a plugin for jQuery to get GET params called .getUrlParams
For POST the only solution is echoing the POST into a javascript variable using PHP, like Moran suggested.
Or you can use this one http://plugins.jquery.com/project/parseQuery, it's smaller than most (minified 449 bytes), returns an object representing name-value pairs.
why not use good old PHP? for example, let us say we receive a GET parameter 'target':
function getTarget() {
var targetParam = "<?php echo $_GET['target']; ?>";
//alert(targetParam);
}
Keep it simple
replace VARIABLE_KEY with the key of the variable to get its value
var get_value = window.location.href.match(/(?<=VARIABLE_KEY=)(.*?)[^&]+/)[0];
With any server-side language, you will have to emit the POST variables into javascript.
.NET
var my_post_variable = '<%= Request("post_variable") %>';
Just be careful of empty values. If the variable you attempt to emit is actually empty, you will get a javascript syntax error. If you know it's a string, you should wrap it in quotes. If it's an integer, you may want to test to see if it actually exists before writing the line to javascript.
You can try Query String Object plugin for jQuery.
Here's something to gather all the GET variables in a global object, a routine optimized over several years. Since the rise of jQuery, it now seems appropriate to store them in jQuery itself, am checking with John on a potential core implementation.
jQuery.extend({
'Q' : window.location.search.length <= 1 ? {}
: function(a){
var i = a.length,
r = /%25/g, // Ensure '%' is properly represented
h = {}; // (Safari auto-encodes '%', Firefox 1.5 does not)
while(i--) {
var p = a[i].split('=');
h[ p[0] ] = r.test( p[1] ) ? decodeURIComponent( p[1] ) : p[1];
}
return h;
}(window.location.search.substr(1).split('&'))
});
Example usage:
switch ($.Q.event) {
case 'new' :
// http://www.site.com/?event=new
$('#NewItemButton').trigger('click');
break;
default :
}
Hope this helps. ;)
jQuery plugins seem nice but what I needed is a quick js function to parse the get params.
Here is what I have found.
http://www.bloggingdeveloper.com/post/JavaScript-QueryString-ParseGet-QueryString-with-Client-Side-JavaScript.aspx
If your $_GET is multidimensional, this might be what you're wanting:
var $_GET = {};
document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function () {
function decode(s) {
return decodeURIComponent(s.split("+").join(" "));
}
//handling for multidimensional arrays
if(decode(arguments[1]).indexOf("[]") > 0){
var newName = decode(arguments[1]).substring(0, decode(arguments[1]).length - 2);
if(typeof $_GET[newName] == 'undefined'){
$_GET[newName] = new Array();
}
$_GET[newName].push(decode(arguments[2]));
}else{
$_GET[decode(arguments[1])] = decode(arguments[2]);
}
});
simple, but yet usefull to get vars/values from URL:
function getUrlVars() {
var vars = [], hash, hashes = null;
if (window.location.href.indexOf("?") && window.location.href.indexOf("&")) {
hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
} else if (window.location.href.indexOf("?")) {
hashes = window.location.href.slice(window.location.href.indexOf('?') + 1);
}
if (hashes != null) {
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars[hash[0]] = hash[1];
}
}
return vars;
}
I found it somewhere on the internet, just fixed few bugs
Use following function:
var splitUrl = function() {
var vars = [], hash;
var url = document.URL.split('?')[0];
var p = document.URL.split('?')[1];
if(p != undefined){
p = p.split('&');
for(var i = 0; i < p.length; i++){
hash = p[i].split('=');
vars.push(hash[1]);
vars[hash[0]] = hash[1];
}
}
vars['url'] = url;
return vars;
};
and access variables as vars['index'] where 'index' is name of the get variable.
My approach:
var urlParams;
(window.onpopstate = function () {
var match,
pl = /\+/g, Regex for replacing addition symbol with a space
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
query = window.location.search.substring(1);
urlParams = {};
while (match = search.exec(query))
urlParams[decode(match[1])] = decode(match[2]);
})();
Just for the record, I wanted to know the answer to this question, so I used a PHP method:
<script>
var jGets = new Array ();
<?
if(isset($_GET)) {
foreach($_GET as $key => $val)
echo "jGets[\"$key\"]=\"$val\";\n";
}
?>
</script>
That way all my javascript/jquery that runs after this can access everything in the jGets. Its an nice elegant solution I feel.

Categories