Get URL parameters with Javascript - javascript

Hi I have the following tag inside my HTML:
<script type="text/javascript" src="http://XX/teste1.php?BLABLABLA"></script>
Is there somewhay inside teste1.php, using JS to retrieve the parameters BLABLABLA? If I use window.location.href I get the index.php location (of course) but I need to get the parameters sent to the external resource using JS and not PHP.

I think I understood what you are after. Take a look the following fiddle.
http://jsfiddle.net/gK58u/2/
You can see I'm manually loading in jQuery, and then getting the src from the script declaration.
===================
HTML Add an id to your script declaration
<script id="jquerysrc" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js?key=test"></script>
Javascript
$(document).ready(function() {
var scriptsource = "";
scriptsource = $("#jquerysrc").attr("src");
alert(scriptsource);
});
This will allow you see the url that your external js file is coming from. This is more a point in the right direction.

You can try this, without using jQuery.
var scripts = document.getElementsByTagName('script'),i,src;
for(i=0;i<scripts.length;i++){
src = scripts[i].src;
if (src && src.indexOf('?')>=0){
console.log(src.substring(src.indexOf('?')+1));
}
}

Currently JavaScript don't have any of the built-in function for such purpose. What you're talking about i.e. BLABLABLA is known as Query String. Which is attacked to the URL to make a dynamic web page (change the content depending on the condition)
First Method
Is to get the whole URL, and then replacing the URL with empty string and so on to get only the last element.
Second method
Another answer was posted with a function (custom function, not a builtIn function). In which you pass on a parameter to the method, which gets the parameter values for you. It is easy to understand too.
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
To call the function, you use getParameterByName('prodId'). Use it inside a function or variable and you're good to go.

It seem you don't understand how PHP and JS works together.
Php generate HTML (maybe JS and CSS too). Then when this html is loaded by a client, JS is executed.
To get it in PHP or JS, you can use regex or modify the url from ?BLABLABLA to ?key=BLABLABLA. In PHP, "BLABLABLA" will be stored in $_GET['key']
EDIT :
well I misunderstood your question.
From "How to retrieve GET parameters from javascript?" :
-------------------------
With the window.location object. This code gives you GET without the question mark.
window.location.search.replace( "?", "" );
-------------------------
From your example it will return BLABLABLA
window.location DOC
EDIT2 :
When you generate your Javascript in teste.php, you should do this :
$str = "";
foreach ($_GET as $key => $value) {
$str = $key;
}
echo "var getParam = ".$str.";";
I don't see how to avoid foreach if you don't know what is given. You may have to rebuilt the parameters string ("?xxx=sss&ddd=zz...")
Now you JS variable getParam should contains BLABLABLA
Apolo

Related

Personalize page content with data passed through a link

I'm building a page for digital campaigns and I'd like to personalize the content of that page based on who referred users there.
For example, A sends B a link to this page, I generate the link to be sent by A automatically on his dashboard. When B clicks the link, I want the page title to say "Hey, A referred you here"
I know the solution to this might be simple but I'm not very awesome with web dev yet. How do I
Pass this information through the link?
Collect the information on the page and put it in as part of the content?
Looking forward to suggestions for most effective implementation
Theory
You can pass information to a page through the URL using URL parameters. This method of posting data is called GET
For example, take this URL:
example.com?key1=val1&key2=val2
You can send any number of parameters using the syntax key=value (note, value is not enclosed in quotes), and separate each one with an &. You must put a question mark between the URL and the parameters.
JavaScript
You can then retrieve the URL parameters using the following JavaScript code. Insert the following at the beginning of your page.
//To get Query Strings with JS
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]);
})();
To get the value of a URL parameter, do the following:
var x = urlParams.key1; // x will be "val1"
PHP
To retrieve the URL parameters using PHP, it is much simpler. You don't need to add any code to the beginning of the page as with JavaScript, as it is an inbuilt feature of PHP. Just do the following:
$x = $_GET["key1"]; // $x will be "val1"
Practice
In your case, you could make the URL show for user Albert, his unique URL for sharing could be
example.com?sender=Albert
And on your website you could put
<script>
if (urlParams.hasOwnProperty("sender")) {
document.write("Hey, " + urlParams.sender + " reffered you here!");
}
</script>

Is there any way to get ONLY the PHP page of the current page using javascript?

I want to get the my exact location (only PHP page) using javascript, I'm currently using window.location to get the exact url for example: localhost/empc/myfolder/functions.php what is the code if I want to get only functions.php as a result? Is it possible? Thank you.
You can use location object to do this, To remove the "/" before the file name you can use substring method.
location.pathname.substring(location.pathname.lastIndexOf("/") + 1);
you can try this pretty simple
var url = 'localhost/empc/myfolder/functions.php';
var url = url.split('/');
alert(url.pop());
It is possible. Use the javascript split function to separate the string into pieces and then access the last element to get the file name:
var str = "localhost/empc/myfolder/functions.php";
var arr = str.split("/");
alert(arr[arr.length-1]); //this will alert functions.php

Why am I getting an error when trying to add the src attribute to an img tag using JavaScript within Colfusion?

I am using ColdFusion to connect to and execute methods from a Web Service. I store the contents of the returned xml string in to a ColdFusion array then I convert the ColdFusion array into a JavaScript array, so that I may populate the content of my HTML document.
My problem arises when trying to add a photo to a unordered list called "agent_photo_list". Specifically when I call the .setAttribute method. It seems to involve the 'src' parameter. The JavaScript code works as I expect when it is not inside the cfscript tag and WriteOutput method. I have researched the problem, I haven't been able to find a reference that is sufficiently similar. I am still having trouble understanding what my problem is. I have included my code below:
cfscript>
WriteOutput('
<script language = "JavaScript">
var #ToScript(array, "jsArray")#
var agent = jsArray[0];
document.getElementById("output").innerHTML = agent.firstname + " " + agent.lastname;
var imgurl = "_images/agentphoto.jpg";
var node = document.createElement("LI");
var imgnode = (document.createElement("IMG"));
imgnode.setAttribute('src', "imgurl");
node.appendChild(imgnode);
document.getElementById("agent_photo_list").appendChild(node);
</script>
')
</cfscript>
I am using a jpg file located in my _images folder for testing purposes, I will later change it to agent.photourl.
The error I get is provided below:
Invalid CFML construct found on line 117 at column 35.ColdFusion was
looking at the following text:<p>src</p><p>The CFML
compiler was processing:<ul><li>An expression beginning
with WriteOutput, on line 111, column 17.This message is usually
caused by a problem in the expressions structure.<li>A script
statement beginning with WriteOutput on line 111, column
17.<li>A cfscript tag beginning on line 102, column 10.</ul> The specific sequence of files included or processed is: C:\inetpub\wwwroot\webservice.cfm, line: 117
I am curious to why my JavaScript is functional inside the cfscript tag until calling the setAttribute method and why it is functional outside the cfscript tag.
I will appreciate your insight. Thank you.
You need to wrap the src in "". Also, add the ";" at the end of WriteOutput closure. The below code should work for you.
<cfscript>
WriteOutput('
<script language = "JavaScript">
var #ToScript(array, "jsArray")#
var agent = jsArray[0];
document.getElementById("output").innerHTML = agent.firstname + " " + agent.lastname;
var imgurl = "_images/agentphoto.jpg";
var node = document.createElement("LI");
var imgnode = (document.createElement("IMG"));
imgnode.setAttribute("src", "imgurl");
node.appendChild(imgnode);
document.getElementById("agent_photo_list").appendChild(node);
</script>
');
</cfscript>

Injecting and executing JavaScript string in a specific HTML element

I have received the latest Disqus comments string (JavaScript code) from the server using ajax call that has document.write code in it.
I want the page to execute this code inside a specific DIV (by it Id, which is '#recent-comments') in the page, how do I do that?
I use jQuery 2.1.1.
Its a bit nasty but you could eval it inside a closure function:
var message =" document.write('hello'); ";
eval("(function(){"+
"var document = {write:function(text){$('#divName').html(text)}}; " +
message +
" })();");
JSFiddle DEMO (I've had to change write to wrie otherwise jsfiddle disallows it, just need to change back for your case)
Since it is coming as a string, you need to create a script element and put the string (inside document.write) as a element to the div.
var sampleStr = "document.write(\"Hello World\");";
var str, scriptElement = document.createElement('script');
str = sampleStr.replace(/["']/g, '"');
str = str.replace(/"document.write/g, "");
scriptElement.innerHTML = str;
$('#div1').append(scriptElement);
Updated Fiddle

Window.Open Java Script Variable

I am trying to pass a javascript variable to a new window that opens, however if i add a name of "_self", the variable will not be passed:
This won't work, appointmentId is undefined:
var w = window.open("../calendar/appointment.html","_self");
w.appointmentId = appt.id;
This does work:
var w = window.open("../calendar/appointment.html");
w.appointmentId = appt.id;
How can I pass a variable using the _self name, so a new tab/window is not opened?
The variables I am passing are huge. They would take up the URL limit. Sorry I didn't specify this earlier.
Thanks
An alternative is to pass the variable in the querystring.
To redirect:
window.location = "../calendar/appointment.html?appt_id=" + appt.id
On page load:
<script type="text/javascript">
// http://stackoverflow.com/a/901144/1253312
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)");
var results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
window.appointmentId = getParameterByName('appt_id');
</script>
An alternate way to do this is via window.location. For example:
window.location = "../calendar/appointment.html"; // this will send the user here in the current window
In addition, variables are typically passed from page-to-page via the use of a QueryString (sometimes known as GET variables). These typically appear after a question mark. In your case, you could pass the variable like this:
window.location = "../calendar/appointment.html?appointmentId=" + appt.id;
// ../calendar/appointment.html?appointmentId=113
You could also pass the variable after a hash mark:
window.location = "../calendar/appointment.html#" + appt.id;
// ../calendar/appointment.html#113
If you go with the second option, then you can read the variable via location.hash. If you pass it via the QueryString, then you can extract the variable back out of the URL as shown in this question:
How can I get query string values in JavaScript?
window.open can take 3 parameters
https://developer.mozilla.org/en-US/docs/Web/API/Window.open
The second parameter you are passing is the name of the created window.
This is why you don't have it inside the window.
window.open(strUrl, strWindowName[, strWindowFeatures])
Information about supported features can be found in the given url.
The reason why the code you posted doesn't work is because when you use _self, the old document gets cleaned up before the new document can be loaded. Thus, there is no moment in time when the two can communicate synchroneously.
This answer for a slightly different question, but with the same root cause gives several asynchronous communication approaches:
Options you can use are :
Adding it as a parameter using the hash tag (second.php#tmpstr=aaaaaa
Using cookies (there is a nice jQuery cookie plugin)
Moving your whole page into a iFrame (not recommended) and redirecting only the main frame.
Note that using the hash tag is slightly better than using the query string suggested by the other answers because your variable will not end up on the request to the server.
You can use the browser's session storage.
https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage
Before redirecting:
sessionStorage.setItem("appointmentId", appt.id);
Redirect:
window.location = "../calendar/appointment.html";
When appointment.html loads:
window.appointmentId = sessionStorage.getItem("appointmentId");

Categories