How to get variable from url for .js file? - php

Example: Suppose the current page url(window.location.href) is http://example.com/page.html
The html page source code is...
<html><head></head><body>
<script src="http://example.com/script.js?user=Ankit&ptid=18"></script>
</body></html>
Now I need to use 'src' variables in script.js
And the script file script.js should return
var a="Ankit"
var b="18"
Can we use something like echo $_GET like in php?

Found this here. If you're using jQuery, this should be helpful.
function getURLParameter(name) {
return decodeURI(
(RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
);
}
This is a javascript function that will return the value in the url of a parameter that you pass to it. In this case, you would call it with
var a = getURLParameter("user");
var b = getURLParameter("ptid");
EDIT: I misinterpreted the original version of your question as asking about getting parameters to the .html page being loaded. I just tested this solution, and it does not work within the .js file itself. However, if you declare your variables in the .js file, and place this in the onLoad event, removing var from in front of a and b, it should assign the variables correctly.

Maybe outdated but a nice piece of code and would exactly do what was asked for in OP
// Extract "GET" parameters from a JS include querystring
function getParams(script_name) {
// Find all script tags
var scripts = document.getElementsByTagName("script");
// Look through them trying to find ourselves
for(var i=0; i<scripts.length; i++) {
if(scripts[i].src.indexOf("/" + script_name) > -1) {
// Get an array of key=value strings of params
var pa = scripts[i].src.split("?").pop().split("&");
// Split each key=value into array, the construct js object
var p = {};
for(var j=0; j<pa.length; j++) {
var kv = pa[j].split("=");
p[kv[0]] = kv[1];
}
return p;
}
}
// No scripts match
return {};
}
Source: James Smith - Extract GET Params from a JavaScript Script Tag

I know it's an old post, but as I was looking for something like that I came across it. The very simple solution I finally adopted is the following one:
<html><head></head><body>
<script>
var a = "Ankit";
var b = 18;
</script>
<script src="http://example.com/script.js?user=Ankit&ptid=18"></script>
</body></html>
If you absolutely want to complicate your life and use Lahmizzar's solution, I would recommend to give an id to your tag script, which avoids a greedy function.
HTML :
<script src="http://example.com/script.js?user=Ankit&ptid=18" id="myScript"></script>
JS :
function getParams(script_id) {
var script = document.getElementById(script_id);
if(script) {
// Get an array of key=value strings of params
var pa = script.src.split("?").pop().split("&");
// Split each key=value into array, the construct js object
var p = {};
for(var j=0; j<pa.length; j++) {
var kv = pa[j].split("=");
p[kv[0]] = kv[1];
}
return p;
}
// No scripts match
return {};
}
getParams("myScript");

Related

Getting parameters from page url

So, here's the main code, which checks the URL of the current page for the string ?a= then sets the variable ee_roomname to anything after that.
<script type="text/javascript">
var ee_roomname = unescape(location.href.substring(location.href.lastIndexOf("?a=")+1))
if(ee_roomname.indexOf("?") != -1) ee_roomname = "";
</script>
But what, if I want to add more variables, maybe after this value. For ex. here's a possible url:
http://abc.de/fg.html?a=hijk
Thus, the variable ee_roomname will be set to hijk
Now if we add some more tags, it will look like this:
http://abc.de/fg.html?a=hijk&b=lmno&c=pqrs
Now ee_roomname will be set to hijk&b=lmno&c=pqrs, which is not what I want.
I want the code to only track the a variable/parameter's value from the URL.
What needs to be changed, and how, in order to make it work?
Maybe provide a code I can use, too. (not too big fan of "do this and this" and such)
Here is a function to retrieve url parameters
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
How to retrieve the url parameters in your javascript
var first = getUrlVars()["id"];
var second = getUrlVars()["page"];
alert(first);
alert(second);
View the Source
For your bonus: if you split the string at the '?' and take the first half, that will give you the "pure" absolute url.
to answer the first question, you could also try:
<script>
var query = window.location.search.substring(1);
var getv = query.split("&");
var pair = new Array();
for (var i=0; i < getv.length; i++) {
pair[i] = getv[i].split("=");
}
</script>
pair is an array of all get variables and values like:
[["h", "1"], ["g", "2"]] if ?h=1&g=2
hope that helps.
Try to parse the entire url using this URL Parsing library in JavaScript.

Settings Selector Dynamically in JQuery

I have a table whose values are being generated dynamically with PHP, including the id and name attributes (e.g. id="question_".
How can I set an element attribute with this in mind? For example, I have a div whose text will change after a successful ajax call, but the id is dynamic.
I have tried making the following test function, and calling it on an onclick event:
function approve(question_id)
{
var div = 'suggestion_status_' + question_id;
$('#div').html('test');
}
But that does not work. How can make the value of variable 'div' the selector?
The problem with your example is that div is a variable, not a string; so the following will work:
function approve(question_id)
{
var div = 'suggestion_status_' + question_id;
$('#' + div).html('test');
}
Or even:
function approve(question_id)
{
$('#suggestion_status_' + question_id).html('test');
}
Another approach would be to utilize classes, and add a known class to your elements. Without seeing the full HTML, I can't provide a full example, but something like this would be the way to go:
$('.yourCommonClass').bind('click', function () {
var that = this;
jQuery.get('/accept.php', {
id: this.id
}, function (msg) {
$(that).html('Accepted!');
});
});
Bearing in mind that jQuery.get parameters are the target url, optional data attributes that are encoded in the request, and then a callback function.
you defined div as a variable then used it as a string try concatenating it instead
function approve(question_id)
{
var div = 'suggestion_status_' + question_id;
$('#'+ div).html('test');
}
or shorten like this
function approve(question_id)
{
$('#suggestion_status_' + question_id).html('test');
}
$('#suggestion_status_' + question_id).html('test');
$('#suggestion_status_' + question_id)
I think you want this:
function approve(question_id)
{
var div = 'suggestion_status_' + question_id;
$('#'+div).html('test');
}
this. $('#suggestion_status_' + question_id).html('test');

jQuery Splitting of 2 values

I am trying to split the values of an array i'm generating through an autosuggest.
The output of the values are as such:
[
{"value":"12","name":"Solid Fuel Fire Installers"},
{"value":"11","name":"Oil Engineers & Boiler Fitters"}
]
I want to extract the values 12 & 11 and store as a variable so I can save these to a database through php. This is what I have tried so far and to no success:
<script type="text/javascript">
var arr = $(".as-values").val().split(",");
var category_1=arr[0];
var category_2=arr[1];
var category_3=arr[2];
</script>
I only have 3 categories as I have set a limit on the amount they can add (3).
Many thanks in advance.
That looks like json. Why not just access it as a native JS structure?
var json = $(".as-values").val();
data = jquery.parseJSON(json)
alert(data[0].name); // solid fuel fire installers
The array is an array of objects, not strings, so why not treat them as such?
<script type="text/javascript">
var arr = $(".as-values").val();
var category_1=arr[0].value;
var category_2=arr[1].value;
var category_3=arr[2].value;
</script>
Not sure what you're trying to do. Does this sound like it?
var values = '[{"value":"12","name":"Solid Fuel Fire Installers"},{"value":"11","name":"Oil Engineers & Boiler Fitters"}]';
values = $.parseJSON(values);
var submitValues = {};
$.each( values, callback(i, element){
submitValues[element.value] = element.name;
});
The string you're trying to use is valid json so you should be able to just decode the string with native functions in js that would be JSON.parse(json_string, reviver) in php you would use json_decode($json).
Decoding the string will give you an object/array you should be able to work with easily.
(This is what you want right?)
Is your question how to access an element by value of its property? You could do this:
var elements = [
{"value":"12","name":"Solid Fuel Fire Installers"},
{"value":"11","name":"Oil Engineers & Boiler Fitters"}
]; // Retrieve however you want
var element;
for(var i = 0; element = elements[i]; i++) {
if(element.value == 11) {
// It's number 11, for example
}
}
Of course you should probably put that in a function:
function findByProperty(elements, property, value) {
var i, element;
for(i = 0; element = elements[i]; i++) {
if(element[property] === value) return element;
}
return null;
}
// ... define 'elements' as before
var numberEleven = findByProperty(elements, 'value', "11");
Since you already have an array of a valid json you dont need to parse it. Just try this.
var arr = [
{"value":"12","name":"Solid Fuel Fire Installers"},
{"value":"11","name":"Oil Engineers & Boiler Fitters"}
]
var category_1=arr[0].name;
var category_2=arr[1].name;

need a script to split and assign values Jquery

I am trying to separate and reassign values in a variable. What I have is
#&first=1&second=2
can anyone help with a script that will separate and assign this values to another variable so it would be like
var first= val.(first);
var second= val.(second);
I am new to jquery so I am not even sure if I am using the correct syntax.
Thanks
You could do something like this:
var val = "#&first=1&second=2";
var first = gup(val, "first");
var second = gup(val, "second");
function gup(str, name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(str);
if (results == null) return "";
else return results[1];
}
Checkout the example on jsfiddle: http://jsfiddle.net/WxnJq/
Here's the one that breaks down the GET variables in to key/value pairs, which I believe is what you're after: http://snipplr.com/view/12208/javascript-url-parser/
Also, you can take a look at parseURI, a javascript function that can dissect a URL with GET parameters and grab sections.
Sorry for being quick to post, I thought I found the right function the first time.
JQuery has no builtin way of dealing with querystrings, so I use a plugin for this. You can get it here, works great.

How to handle pagination with JQuery and AJAX?

On my site I have the links First, Prev, Next, and Last. These are empty links that are captured and handled by JQuery. However, still being very new to AJAX and JQuery, I'm not sure how to accomplish what I want. I believe I could get this working using post but the only problem is that I want the target page number to go in to the URL in this format:
http://www.mywebsite.com/index.php?page=3
Then on page load I would use the $_GET variable and with the page number I could request the appropriate tables from the database and display them to the user.
Basically what I'm asking is how to make simulate this behavior with JQuery.
You can do something like this:
Javascript:
post:
function pagination(page) {
if (!page)
var page = 1;
$.post("index.php", { page: page }, function(data) {
// data loaded, do something
});
}
or get
function pagination(page) {
if (!page)
var page = 1;
$.get("index.php?page=" + page, function(data) {
// data loaded, do something
});
}
Then, You just have to call the javascript function:
Prev Next
As long as you're requesting this from the same site as the script, you might be able to get away with this.
To load remote content (Google Cross Site Scripting for limitations), jQuery has a simple function to do that:
$('#result').load('ajax/test.html');
This loads test.html into the item with the id of #ajax. Pretty simple.
In order to get the arguments, you can use this script (credit goes to http://jquery-howto.blogspot.com/2009/09/get-url-parameters-values-with-jquery.html):
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
The usage information is avaliable there too.

Categories