It is possible to parse url with # in php? - javascript

For example:
I declared url in javascript:
<script>
window.location.href = "signup.php#year=" + myyear;
</script>
And in php, I am trying to get #year:
<?php
if(isset($_GET['year'])){
$year = $_GET['year'];
}
?>
thank you in advance!

in simple terms we use ? or / to get the variables and not #

don't used # sign
<script>
var myyear;
window.location.href = "signup.php?year=" + myyear;
</script>
and you can get
<?php
if(isset($_GET['year'])){
$year = $_GET['year'];
}
?>

Actually you just missing one thing on your href.
window.location.href = "signup.php?year=" + myyear
this code results to url with *signup.php?year=2017
Php
You can get it using $_GET['year'] now.

Convert the url string to a PHP url object with the function parse_url and dereference its "fragment" key like this:
$url=parse_url("www.example.com/example/?shareURL&adherentID=ascd#123");
echo $url["fragment"];
The above code returns 123. working example here - http://codepad.org/r8icljcW

If you want to make use of $_GET then you should use a ? instead of #. The ? symbol is the indicator for a GET, not the #.
So simply change your URL structure to:
<script>
window.location.href = "signup.php?year=" + myyear;
</script>
and then, as you already did, grab the value with the GET.
<?php
if(isset($_GET['year'])){
$year = $_GET['year'];
}
?>
If you want to use more parameter, use the &symbol to separate them. You can add as many as you want, you just have to follow the `&key1=value1&key2=value2? structure and you can expand it as long as you want. Example:
<script>
window.location.href = "signup.php?year=" + myyear&month=5;
</script>
Now you could do:
<?php
if(isset($_GET['year'])){
$year = $_GET['year'];
$month = $_GET['month']; // Would assign 5 to month.
}
?>

Related

Why hash(#) not remove from a string using str_replace in PHP?

I have tried below code
<script type="text/javascript">
var hasvalue = window.location.hash;
</script>
<?php
$ValHas = "<script>document.writeln(hasvalue);</script>";
echo $ValHas."<br>"; // Display #123-12555
echo str_replace("#","",$ValHas); // Display again #123-12555
?>
What I am missing there?
$ValHas is still a string in PHP, with a value of "<script>document.writeln(hasvalue);</script>". It has no #s. It doesn't get turned into '#123-12555 ' until the client's Javascript evaluates the function.
If you want to remove the hash client-side, do this:
var hasvalue = window.location.hash.replace('#', '');

php ja javascript links and encoding

With scandinavian letters and when encoding them, I have a problem. With code below, javascript add some extra encoding to variable
<script>
function doit(params) {
var url = "/linkto/code.php" + params;
window.open(url,"Doit","width=750, height=600");
}
</script>
<?php
$values = urlencode($var1); // encoding skandinavian letters
$param = '?test='.$values; // add them to variable
echo 'Do it!'; // link to page
?>
When changing code above to php, changed does not happened and problem go away.
$values = urlencode($var1); // encoding skandinavian letters
$param = '?test='.$values; // add them to variable
// link to page
echo '<a href="/linkto/code.php"'.$param.'>Do it!</a>';
Hi all again,
I cannot make it work, no difference between utf-8 or iso-8859-1.
Result is something else, when using javascript-function or direct link.
You can try it here:
http://www.ajl.fi/tmp/test.php
Here is codes:
test.php:
<script type="text/javascript">
function doIt(params) {
var url = "doit.php" + params;
window.open(url,"doit");
}
</script>
<?php
$var1 = 'pähkinä';
$var1 = urlencode($var1);
echo sprintf("Do it - call",$var1)."<br>";
echo sprintf("Do it - link",$var1);
?>
and here is doit.php:
<?php
var_dump($_GET);
?>
In ist code, you have two issues in this code
1) Short tag will not work inside the <?php ?> here:
echo 'Do it!'; // link to page
2) You forgot to add quotes here:
window.open(url,"Doit",width=750, height=600"); //missing quote here
Modified Code:
<?php
$var1 = 'p%E4hkin%E4';
$values = urlencode($var1); // encoding skandinavian letters
$param = '?test='.$values; // add them to variable
?>
Do it!
<script type="text/javascript">
function doit(params) {
var url = "/linkto/code.php" + params;
console.log(url);
window.open(url,"Doit","width=750, height=600");
}
</script>
I answer to myself - Solved.
IE, Edge and Chrome, all working ok on both cases. Firefox has a problem. When using
Do it!
result is not correct, but when using
Do it!
seems to work on all browsers

Set the value/text of a div using javascript/jquery - inside a php LOOP

I want to set the value/text of a div using javascript/jquery inside a loop but I don't know how to implement it. I need help with this one guys.
Objectives:
Retrieve data from database.
Set the value of an element using javascript/jquery (inside a loop) from the database.
Make the value a link
I have this a_link column from links table with the ff. values:
- www.google.com
- https://www.google.com
- www.stackoverflow.com
And here is my code:
<?php
$querylink = "SELECT * from links";
$resultlink = mysql_query($querylink);
while ($rowlink = mysql_fetch_array($resultlink))
{
$thelink = $rowlink['a_link'];
?>
<div class = "row">
<span id = "linkhere"></span>
</div>
<script>
var link = "<?php echo $thelink; ?>";
$("#linkhere").html(urlify(link));
function urlify(text) {
var urlRegex = /(((https?:\/\/)|(www\.))[^\s]+)/g;
//var urlRegex = /(https?:\/\/[^\s]+)/g;
return text.replace(urlRegex, function(url,b,c) {
var url2 = (c == 'www.') ? 'http://' +url : url;
// return '<span style = "color:blue;text-decoration:underline">' + url + '</span>';
return '' + url + '';
})
}
</script>
<?php
}
?>
Any help would be highly appreciated. Thanks.
#aimme is technically not wrong about using a different database library. Please read "Why shouldn't I use mysql_* functions in PHP?" for reasons why not to use mysql_ and for some neat alternatives, some tutorials, and some good reads. (yes, all in the same page! just scroll down)
I think you're trying to:
display a <div> of class 'row'
with an <a> tag inside that uses the 'a_link' column of the 'links' table as the href and the label.
The href for the tag must always have a scheme (http://).
Just PHP and HTML
<?php
$querylink = "SELECT * from links";
$resultlink = mysql_query($querylink);
while ($rowlink = mysql_fetch_array($resultlink))
{
$theLink= $rowlink['a_link'];
$regexMatches = array();
// removed (what seemed to be) needless groups in regex
$urlFound = preg_match("#((https?:\/\/|www\.)[^\s]+)#",$theLink,$regexMatches);
if($urlFound === 1) {
// only add http:// if http:// was not detected
$href = ($regexMatches[2] === "www." ? "http://" : "") . $theLink;
?>
<div class="row">
<?php echo $theLink; ?>
</div>
<?php }
}
?>
This code won't echo a row if a_link doesn't contain either 'http://' or 'www.' in it. so google.com will not be displayed.
Of note, as written, the regex will work on "urls" like 'applewww.google.com'. Don't know if that matters. Adding a '^' to the beginning of the regex may solve the problem (like so:preg_match("#^((https?:\/\/|www\.)[^\s]+)#",$theLink,$regexMatches);)
A (better|different) solution could use parse_url($url)
<?php
$querylink = "SELECT * from links";
$resultlink = mysql_query($querylink);
while ($rowlink = mysql_fetch_array($resultlink))
{
$theLink= $rowlink['a_link'];
$href = (parse_url($theLink,PHP_URL_SCHEME) === NULL ? "http://" : "") . $theLink;
?>
<div class="row">
<?php echo $theLink; ?>
</div>
<?php
}
?>
However, using parse_url() would mean any old string would be displayed (while the first solution would not display any links that didn't have either http:// or www.) but since your pulling from a table called 'links' it's probably safe to assume everything is a valid path.
That's not how it works, that's not how any of this works
Now let's assume that you really need to use Javascript to process your generated links (which is not).
You first need to separate your Javascript code from your PHP code. You will only use Javascript once you have fetched your data and generated some output.
I guess you just want some kind of working code
<?php
$querylink = "SELECT * from links";
$resultlink = mysql_query($querylink);
while ($rowlink = mysql_fetch_array($resultlink)) :
$link = $rowlink['a_link'];
?>
<div class="row">
</div>
<?php
endwhile;
?>
<script type="text/javascript">
$(function() {
$('.row a').each(function() {
var urlified = urlify($(this).data('url'));
$(this).attr('href', urlified.url)
.text(urlified.label);
});
});
function urlify(text) {
var urlRegex = /(((https?:\/\/)|(www\.))[^\s]+)/g;
return text.replace(urlRegex, function(url,b,c) {
var label = (c == 'www.') ? 'http://' +url : url;
return {url: url, label: label};
});
}
</script>
First i want to advice that use PDO or mysqli instead of mysql. as it
is vulnerable to sql injection and its depreciated.
"I want to set the value/text of a div using javascript/jquery inside a loop but I don't know how to implement it. I need help with this one guys."
for that i would say Php is a server side language whereas javascript is a client side language. and Ajax is the way to manipulate client side from server vice versa, without refreshing the whole page.
below is just a demonstration that i edited little bit from your code to show the separation of server side and client side code and to just give an idea how it works.I don't know whether the code will work or not. haven't tested. php code (server side) will be executed first but could control the display of it using javascript(client side) functions inside document.ready() or window.load() to apply the affects as soon as possible.Through this we could bring changes to the links that we want before its being shown to the client . For each of the link retrieved and displayed you could use a specific class and jquery .each() function to apply certain fix to the selected link as Lyes BEN mentioned above or all the elements with a specific class could be manipulated as a whole without using .each.
<?php
$querylink = "SELECT * from links";
$resultlink = mysql_query($querylink);
while ($rowlink = mysql_fetch_array($resultlink))
{
$thelink = $rowlink['a_link'];
echo '<div class = "row">
<span id = "linkhere">
</span>
</div>';
}
?>
<script>
$("#linkhere a").html(urlify(link));
function urlify(text) {
var urlRegex = /(((https?:\/\/)|(www\.))[^\s]+)/g;
//var urlRegex = /(https?:\/\/[^\s]+)/g;
return text.replace(urlRegex, function(url,b,c) {
var url2 = (c == 'www.') ? 'http://' +url : url;
// return '<span style = "color:blue;text-decoration:underline">' + url + '</span>';
return '' + url + '';
})
}
</script>
You can implement this using php with parse_url function (http://php.net/manual/en/function.parse-url.php) to get different components.
In parse_url, there is 'scheme' key for http or https.
Then to do this with php, just call formatUrl function to make the url
<?php
function formatUrl($url)
{
$urlData = parse_url($url);
if(!isset($urlData['scheme'])) {
$url = 'http://' . $url;
}
return '' . $url . '';
}
?>
<?php
$querylink = "SELECT * from links";
$resultlink = mysql_query($querylink);
while ($rowlink = mysql_fetch_array($resultlink))
{
$thelink = $rowlink['a_link'];
?>
<div class = "row">
<span id="linkhere"><?php echo formatUrl($thelink)?></span>
</div>
<?php
}
?>

How can i use PHP variable (fetch_array) on JS ? (json encode)

I want to use code like this in script for my functions:
<script>
function selectCust(){
var data = <?php echo json_encode("$rs['name']"); ?>;
document.getElementById("txtfield").value = data;
}
</script>
I didn't work, i didn't want to use the hidden field. So, how will it work in simple way. thank you.
Try this one
<script>
function selectCust(){
var data = "<?php echo json_encode($rs['name']); ?>";
document.getElementById("txtfield").value = data;
}
</script>
Drop those double quotes around PHP variable:
<script>
function selectCust(){
var data = <?php echo json_encode($rs['name']); ?>;
document.getElementById("txtfield").value = data;
}
</script>
Otherwise PHP will parse that string literally and you will just put "$rs['name']" string into your txtfield element.

Keep GET-Values saved

I have function like this:
function SetPageShow (obj)
{
window.location.href="?CMD=PAGEROWS&PARA="+obj.options[obj.selectedIndex].text;
}
and it works fine until I have a page with another GET-values like
http://protectneu/main.php?site=mitarb&liz=260
. then when I call the function SetPageShow, the URL will be
http://protectneu/main.php?CMD=PAGEROWS&PARA=25
and the other values(mitarb and liz) are getting lost. Is there a way to keep them saved and just add the new paramethers. The result that I need is:
http://protectneu/main.php?site=mitarb&liz=260&CMD=PAGEROWS&PARA=25
if (window.location.search)
return window.location.href + "&CMD=PAGEROWS&PARA="+obj.options[obj.selectedIndex].text;
else
return window.location.href + "?CMD=PAGEROWS&PARA="+obj.options[obj.selectedIndex].text;
On the PHP side you need to strip out the parameters that you would send via JavaScript, then build a string with the other parameters, like so:
<?php
$params = $_GET;
unset($params['CMD']);
unset($params['PARA']);
?>
<script>
function SetPageShow(obj)
{
var params = '<?php echo http_build_query($params); ?>';
window.location.href = '?' + (params ? params + '&' : '') + "CMD=PAGEROWS&PARA=" + encodeURIComponent(obj.options[obj.selectedIndex].text);
}
Btw, I've also added encodeURIComponent() in JavaScript to perform proper escaping of the selected value.
Consider using PHP's sessions if you want to retain information like this.
<?php
session_start();
$_SESSION['foo'] = $bar;
?>
Then you can refer to this information on other pages by calling session_start() at the beginning of the page.
<?php
session_start();
$bar = $_SESSION['foo'];
?>

Categories

Resources