So I'm making a website that includes a simple javascript/HTML timer. The code for the timer is listed below.
I'm incorporating a tweet system into the website. My aim is for this tweet button to tweet "I lasted (timevariable)". I'm having trouble doing this as the twitter API seems to be kind of restrictive. The only way to configure default tweet text is through query string parameters. Is there any way to incorporate a variable (from the code below) into a query string parameter, or do I need to do this a more complicated way?
I have thought about doing the variable system with php but this code needs to be very lightweight in execution and because of that I would like to avoid php. Even if I did do it with php I would run into the same issue: how to incorporate a variable into a query string parameter that sets the default tweet.
TL;DR: How do I incorporate a variable into a query string parameter (in regards to twitters default tweet text API).
Here is a look at the way that twitter handles default tweet texts:
Tweet it
and here is the code for the counter that I am using.
<label id="minutes">00</label>:<label id="seconds">00</label>
<script type="text/javascript">
var minutesLabel = document.getElementById("minutes");
var secondsLabel = document.getElementById("seconds");
var totalSeconds = 0;
setInterval(setTime, 1000);
function setTime()
{
++totalSeconds;
secondsLabel.innerHTML = pad(totalSeconds%60);
minutesLabel.innerHTML = pad(parseInt(totalSeconds/60));
}
function pad(val)
{
var valString = val + "";
if(valString.length < 2)
{
return "0" + valString;
}
else
{
return valString;
}
}
</script>
Thank you
Here it is: http://jsfiddle.net/7zKAy/
As you'll see, I change the href of the link through javascript. Ignore the CSS and styles, it's just for show and better presentation.
Start by getting a reference to your link and setting up the base of the url you're going to be using:
var butt = document.getElementById('sharebutton');
var basehref = "https://twitter.com/share?text=";
Then, when you have text to send, build the complete URI. This is one way to do it:
// so i want to add "I lasted 345345334 seconds" to the text
basehref = "https://twitter.com/share?text=" + "\"" + encodeURIComponent("I lasted 345345334 seconds") + "\"";
Notice that I manually add the " at the ends of the string and only encode the contents with encodeURIComponent which is what you use if you want to encode part of a URI instead of all of it. If I was to do the entire thing at one, I'd do:
encodeURI(basehref);
then, attach this new href to your button:
butt.setAttribute('href', basehref);
and you're done. The link might be escaped by the browser when you mouse over it, so in the fiddle, check your console to see the actual string that gets applied to the href attribute.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
How can i select the fragment after the '#' symbol in my URL using PHP?
The result that i want is "photo45".
This is an example URL:
http://example.com/site/gallery/1#photo45
If you want to get the value after the hash mark or anchor as shown in a user's browser: This isn't possible with "standard" HTTP as this value is never sent to the server (hence it won't be available in $_SERVER["REQUEST_URI"] or similar predefined variables). You would need some sort of JavaScript magic on the client side, e.g. to include this value as a POST parameter.
If it's only about parsing a known URL from whatever source, the answer by mck89 is perfectly fine though.
That part is called "fragment" and you can get it in this way:
$url=parse_url("http://example.com/site/gallery/1#photo45 ");
echo $url["fragment"]; //This variable contains the fragment
A) already have url with #hash in PHP? Easy! Just parse it out !
if( strpos( $url, "#" ) === false ) echo "NO HASH !";
else echo "HASH IS: #".explode( "#", $url )[1]; // arrays are indexed from 0
Or in "old" PHP you must pre-store the exploded to access the array:
$exploded_url = explode( "#", $url ); $exploded_url[1];
B) You want to get a #hash by sending a form to PHP? => Use some JavaScript MAGIC! (To pre-process the form)
var forms = document.getElementsByTagName('form'); //get all forms on the site
for (var i = 0; i < forms.length; i++) { //to each form...
forms[i].addEventListener( // add a "listener"
'submit', // for an on-submit "event"
function () { //add a submit pre-processing function:
var input_name = "fragment"; // name form will use to send the fragment
// Try search whether we already done this or not
// in current form, find every <input ... name="fragment" ...>
var hiddens = form.querySelectorAll('[name="' + input_name + '"]');
if (hiddens.length < 1) { // if not there yet
//create an extra input element
var hidden = document.createElement("input");
//set it to hidden so it doesn't break view
hidden.setAttribute('type', 'hidden');
//set a name to get by it in PHP
hidden.setAttribute('name', input_name);
this.appendChild(hidden); //append it to the current form
} else {
var hidden = hiddens[0]; // use an existing one if already there
}
//set a value of #HASH - EVERY TIME, so we get the MOST RECENT #hash :)
hidden.setAttribute('value', window.location.hash);
}
);
}
Depending on your form's method attribute you get this hash in PHP by:
$_GET['fragment'] or $_POST['fragment']
Possible returns: 1. ""[empty string] (no hash) 2. whole hash INCLUDING the #[hash] sign (because we've used the window.location.hash in JavaScript which just works that way :) )
C) You want to get the #hash in PHP JUST from requested URL?
YOU CAN'T !
...(not while considering regular HTTP requests)...
...Hope this helped :)
I've been searching for a workaround for this for a bit - and the only thing I have found is to use URL rewrites to read the "anchor". I found in the apache docs here http://httpd.apache.org/docs/2.2/rewrite/advanced.html the following...
By default, redirecting to an HTML anchor doesn't work, because mod_rewrite escapes the # character, turning it into %23.
This, in turn, breaks the redirection.
Solution: Use the [NE] flag on the RewriteRule. NE stands for No
Escape.
Discussion: This technique will of course also work with other special
characters that mod_rewrite, by default, URL-encodes.
It may have other caveats and what not ... but I think that at least doing something with the # on the server is possible.
You can't get the text after the hash mark. It is not sent to the server in a request.
I found this trick if you insist want the value with PHP.
split the anchor (#) value and get it with JavaScript, then store as cookie, after that get the cookie value with PHP
If you are wanting to dynamically grab the hash from URL, this should work:
https://stackoverflow.com/a/57368072/2062851
<script>
var hash = window.location.hash, //get the hash from url
cleanhash = hash.replace("#", ""); //remove the #
//alert(cleanhash);
</script>
<?php
$hash = "<script>document.writeln(cleanhash);</script>";
echo $hash;
?>
You can do it by a combination of javascript and php:
<div id="cont"></div>
And by the other side;
<script>
var h = window.location.hash;
var h1 = (win.substr(1));//string with no #
var q1 = '<input type="text" id="hash" name="hash" value="'+h1+'">';
setInterval(function(){
if(win1!="")
{
document.querySelector('#cont').innerHTML = q1;
} else alert("Something went wrong")
},1000);
</script>
Then, on form submit you can retrieve the value via $_POST['hash'] (set the form)
You need to parse the url first, so it goes like this:
$url = "https://www.example.com/profile#picture";
$fragment = parse_url($url,PHP_URL_FRAGMENT); //this variable holds the value - 'picture'
If you need to parse the actual url of the current browser, you need to request to call the server.
$url = $_SERVER["REQUEST_URI"];
$fragment = parse_url($url,PHP_URL_FRAGMENT); //this variable holds the value - 'picture'
Getting the data after the hashmark in a query string is simple. Here is an example used for when a client accesses a glossary of terms from a book. It takes the name anchor delivered (#tesla), and delivers the client to that term and highlights the term and its description in blue so its easy to see.
setup your strings with a div id, so the name anchor goes where its supposed to and the JavaScript can change the text colors
<div id="tesla">Tesla</div>
<div id="tesla1">An energy company</div>
Use JavaScript to do the heavy work, on the server side, inserted in your PHP page, or wherever..
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
I am launching the Java function automatically when the page is loaded.
<script>
$( document ).ready(function() {
get the anchor (#tesla) from the URL received by the server
var myhash1 = $(location).attr('hash'); //myhash1 == #tesla
trim the hash sign off of it
myhash1 = myhash1.substr(1) //myhash1 == tesla
I need to highlight the term and the description so I create a new var
var myhash2 = '1';
myhash2 = myhash1.concat(myhash2); //myhash2 == tesla1
Now I can manipulate the text color for the term and description
var elem = document.getElementById(myhash1);
elem.style.color = 'blue';
elem = document.getElementById(myhash2);
elem.style.color = 'blue';
});
</script>
This works. client clicks link on client side (example.com#tesla) and goes right to the term. the term and the description are highlighted in blue by JavaScript for quick reading .. all other entries left in black..
We use three query strings that are pulled into form fields before a user submits. src, cst, and cid are the three parameters. cid and cst always need to be updated to the correct value. src will vary, but if none exists on the URL it should add a default one. I have this working, but think there has to be a much quicker, easier, faster way to do all of this.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
var src = "Report";
var cid = "7013475893xfvg";
var cst = "Responded";
var vsrc = "src";
var vcid = "cid";
var vcst = "cst";
var srcstring = "&" + vsrc + "=" + src;
if ('URLSearchParams' in window) {
var searchParams = new URLSearchParams(window.location.search)
searchParams.set(vcid, cid);
searchParams.set(vcst, cst);
var newRelativePathQuery = window.location.pathname + '?' + searchParams.toString();
history.pushState(null, '', newRelativePathQuery);
}
if (!(window.location.href.indexOf(vsrc) > -1)) {
window.location.search += srcstring;
}
</script>
First, the script adds or updates the cid and cst values to the correct ones defined in the variable. Then, the script determines whether "src" is present in the address bar. If it's not present, it adds the src parameter with a default value.
The goal is for this to be limited to at most one redirect, or history record. Ideally, the user will never see a reload, redirect take place and will not be present in their history. This works currently on Google Chrome desktop, but on Safari Mobile history records are created.
Edit: We discovered an issue with this code that also prevents form fields from gathering values if "%20" is any where in the URL. %20 gets converted to a "+" and breaks this process. How can we avoid this?
I have two pages - "page 1" and "page 2". On page 1 there's an text-box with a value of e.g. 100 and a button at the end.
By pressing the button I want javascript to save the value of the textbox in a global (?) variable and jump to page 2. With "window.onload" I want a second Javascript-function to alert the value saved at page1.
Here's my Javascript code:
<script type="text/javascript">
var price; //declare outside the function = global variable ?
function save_price(){
alert("started_1"); //just for information
price = document.getElementById('the_id_of_the_textbox').value;
alert(price); //just for information
}
<script type="text/javascript">
function read_price(){
alert("started_2");
alert(price);
}
On "page 1" I have this send-Button with:
<input class="button_send" id="button_send" type="submit" value="Submit_price" onclick="save_price();"/>
It starts the Javascript function and redirects me correctly to my page2.
But with this ont the second page:
window.onload=read_price();
I always get an "undefined" value of the global variable price.
I've read a lot about those global variables. E.g. at this page: Problem with global variable.. But I can't get it working...
Why is this not working?
Without reading your code but just your scenario, I would solve by using localStorage.
Here's an example, I'll use prompt() for short.
On page1:
window.onload = function() {
var getInput = prompt("Hey type something here: ");
localStorage.setItem("storageName",getInput);
}
On page2:
window.onload = alert(localStorage.getItem("storageName"));
You can also use cookies but localStorage allows much more spaces, and they aren't sent back to servers when you request pages.
Your best option here, is to use the Query String to 'send' the value.
how to get query string value using javascript
So page 1 redirects to page2.html?someValue=ABC
Page 2 can then
read the query string and specifically the key 'someValue'
If this is anything more than a learning exercise you may want to consider the security implications of this though.
Global variables wont help you here as once the page is re-loaded they are destroyed.
You have a few different options:
you can use a SPA router like SammyJS, or Angularjs and ui-router, so your pages are stateful.
use sessionStorage to store your state.
store the values on the URL hash.
To do this, I recommend sending data within the link data. This is a very simple way of doing it without PHP. Simply get the link in the second page and replace the previous link with "".
Page_One.html:
<script>
//Data to be transfered
var data = "HelloWorld";
//Redirect the user
location.replace("http://example.com/Page_Two.html?" + data);
</script>
Page_Two.html :
<script>
//Get the current link
var link = window.location.href;
//Replace all content before ? with ""
link = link.replace("http://example.com/Page_Two.html?","");
//Display content
document.write("Page_One.html contains:" + link + "");
</script>
Hope it helps!
I have a simple Approach rather (Pure JS):
Page One :
Goto Your Info
Note : You've to encode your GTK value (i.e parameter value) in Base64
Next is Page TWO :
<script>
// first we get current URL (web page address in browser)
var dloc= window.location.href;
//then we split into chunks array
var dsplt= dloc.split("?");
//then we again split into final chunk array, but only second element
//of the first array i.e dsplt[1]
var sanitize= dsplt[1].split("=");
// now here comes the tricky part, join all elements into single //string. IT may be the case, that base64 string contain '=' sign, we shall find it
var dlen= sanitize.length;
var FinString= "";
// we will start from 1, bcoz first element is GTK the key we don't // want it
for(i=1;i<dlen;i++)
{
FinString= FinString+sanitize[i];
}
// afterwards, all the Base64 value will be ONE value.
// now we will convert this to Normal Text
var cleantxt= window.atob(FinString);
document.getElementById("yourname").innerHTML= "Your Name is : <b>"+cleantxt+" .";
You can do anything with the parameter decoded info... Like Redirecting visitor
immediately to another page thru a "POST" method form automatically submitted
by Javasript to Lead a php page finally, without an visible parameters, but with
invisible hidden parms.
I have two pages - "page 1" and "page 2". On page 1 there's an text-box with a value of e.g. 100 and a button at the end.
By pressing the button I want javascript to save the value of the textbox in a global (?) variable and jump to page 2. With "window.onload" I want a second Javascript-function to alert the value saved at page1.
Here's my Javascript code:
<script type="text/javascript">
var price; //declare outside the function = global variable ?
function save_price(){
alert("started_1"); //just for information
price = document.getElementById('the_id_of_the_textbox').value;
alert(price); //just for information
}
<script type="text/javascript">
function read_price(){
alert("started_2");
alert(price);
}
On "page 1" I have this send-Button with:
<input class="button_send" id="button_send" type="submit" value="Submit_price" onclick="save_price();"/>
It starts the Javascript function and redirects me correctly to my page2.
But with this ont the second page:
window.onload=read_price();
I always get an "undefined" value of the global variable price.
I've read a lot about those global variables. E.g. at this page: Problem with global variable.. But I can't get it working...
Why is this not working?
Without reading your code but just your scenario, I would solve by using localStorage.
Here's an example, I'll use prompt() for short.
On page1:
window.onload = function() {
var getInput = prompt("Hey type something here: ");
localStorage.setItem("storageName",getInput);
}
On page2:
window.onload = alert(localStorage.getItem("storageName"));
You can also use cookies but localStorage allows much more spaces, and they aren't sent back to servers when you request pages.
Your best option here, is to use the Query String to 'send' the value.
how to get query string value using javascript
So page 1 redirects to page2.html?someValue=ABC
Page 2 can then
read the query string and specifically the key 'someValue'
If this is anything more than a learning exercise you may want to consider the security implications of this though.
Global variables wont help you here as once the page is re-loaded they are destroyed.
You have a few different options:
you can use a SPA router like SammyJS, or Angularjs and ui-router, so your pages are stateful.
use sessionStorage to store your state.
store the values on the URL hash.
To do this, I recommend sending data within the link data. This is a very simple way of doing it without PHP. Simply get the link in the second page and replace the previous link with "".
Page_One.html:
<script>
//Data to be transfered
var data = "HelloWorld";
//Redirect the user
location.replace("http://example.com/Page_Two.html?" + data);
</script>
Page_Two.html :
<script>
//Get the current link
var link = window.location.href;
//Replace all content before ? with ""
link = link.replace("http://example.com/Page_Two.html?","");
//Display content
document.write("Page_One.html contains:" + link + "");
</script>
Hope it helps!
I have a simple Approach rather (Pure JS):
Page One :
Goto Your Info
Note : You've to encode your GTK value (i.e parameter value) in Base64
Next is Page TWO :
<script>
// first we get current URL (web page address in browser)
var dloc= window.location.href;
//then we split into chunks array
var dsplt= dloc.split("?");
//then we again split into final chunk array, but only second element
//of the first array i.e dsplt[1]
var sanitize= dsplt[1].split("=");
// now here comes the tricky part, join all elements into single //string. IT may be the case, that base64 string contain '=' sign, we shall find it
var dlen= sanitize.length;
var FinString= "";
// we will start from 1, bcoz first element is GTK the key we don't // want it
for(i=1;i<dlen;i++)
{
FinString= FinString+sanitize[i];
}
// afterwards, all the Base64 value will be ONE value.
// now we will convert this to Normal Text
var cleantxt= window.atob(FinString);
document.getElementById("yourname").innerHTML= "Your Name is : <b>"+cleantxt+" .";
You can do anything with the parameter decoded info... Like Redirecting visitor
immediately to another page thru a "POST" method form automatically submitted
by Javasript to Lead a php page finally, without an visible parameters, but with
invisible hidden parms.
I have two pages - "page 1" and "page 2". On page 1 there's an text-box with a value of e.g. 100 and a button at the end.
By pressing the button I want javascript to save the value of the textbox in a global (?) variable and jump to page 2. With "window.onload" I want a second Javascript-function to alert the value saved at page1.
Here's my Javascript code:
<script type="text/javascript">
var price; //declare outside the function = global variable ?
function save_price(){
alert("started_1"); //just for information
price = document.getElementById('the_id_of_the_textbox').value;
alert(price); //just for information
}
<script type="text/javascript">
function read_price(){
alert("started_2");
alert(price);
}
On "page 1" I have this send-Button with:
<input class="button_send" id="button_send" type="submit" value="Submit_price" onclick="save_price();"/>
It starts the Javascript function and redirects me correctly to my page2.
But with this ont the second page:
window.onload=read_price();
I always get an "undefined" value of the global variable price.
I've read a lot about those global variables. E.g. at this page: Problem with global variable.. But I can't get it working...
Why is this not working?
Without reading your code but just your scenario, I would solve by using localStorage.
Here's an example, I'll use prompt() for short.
On page1:
window.onload = function() {
var getInput = prompt("Hey type something here: ");
localStorage.setItem("storageName",getInput);
}
On page2:
window.onload = alert(localStorage.getItem("storageName"));
You can also use cookies but localStorage allows much more spaces, and they aren't sent back to servers when you request pages.
Your best option here, is to use the Query String to 'send' the value.
how to get query string value using javascript
So page 1 redirects to page2.html?someValue=ABC
Page 2 can then
read the query string and specifically the key 'someValue'
If this is anything more than a learning exercise you may want to consider the security implications of this though.
Global variables wont help you here as once the page is re-loaded they are destroyed.
You have a few different options:
you can use a SPA router like SammyJS, or Angularjs and ui-router, so your pages are stateful.
use sessionStorage to store your state.
store the values on the URL hash.
To do this, I recommend sending data within the link data. This is a very simple way of doing it without PHP. Simply get the link in the second page and replace the previous link with "".
Page_One.html:
<script>
//Data to be transfered
var data = "HelloWorld";
//Redirect the user
location.replace("http://example.com/Page_Two.html?" + data);
</script>
Page_Two.html :
<script>
//Get the current link
var link = window.location.href;
//Replace all content before ? with ""
link = link.replace("http://example.com/Page_Two.html?","");
//Display content
document.write("Page_One.html contains:" + link + "");
</script>
Hope it helps!
I have a simple Approach rather (Pure JS):
Page One :
Goto Your Info
Note : You've to encode your GTK value (i.e parameter value) in Base64
Next is Page TWO :
<script>
// first we get current URL (web page address in browser)
var dloc= window.location.href;
//then we split into chunks array
var dsplt= dloc.split("?");
//then we again split into final chunk array, but only second element
//of the first array i.e dsplt[1]
var sanitize= dsplt[1].split("=");
// now here comes the tricky part, join all elements into single //string. IT may be the case, that base64 string contain '=' sign, we shall find it
var dlen= sanitize.length;
var FinString= "";
// we will start from 1, bcoz first element is GTK the key we don't // want it
for(i=1;i<dlen;i++)
{
FinString= FinString+sanitize[i];
}
// afterwards, all the Base64 value will be ONE value.
// now we will convert this to Normal Text
var cleantxt= window.atob(FinString);
document.getElementById("yourname").innerHTML= "Your Name is : <b>"+cleantxt+" .";
You can do anything with the parameter decoded info... Like Redirecting visitor
immediately to another page thru a "POST" method form automatically submitted
by Javasript to Lead a php page finally, without an visible parameters, but with
invisible hidden parms.