I have a PHP function on my website as follows:
$url = $_SERVER["REQUEST_URI"];
$x = $url;
$parsed = parse_url($x);
$query = $parsed['query'];
parse_str($query, $params);
unset($params['page']);
$string = http_build_query($params);
which removes the 'page' parameter from the current URL.
What I need to do now however is write the same function but in javascript, to use in an onclick. I have searched and come up with the following solution:
$('#localtab').click(function() {
return location.href=location.href.replace(/&?page=([^&]$|[^&]*)/i, "");
});
this is working but as this is the first ever time I've coded regex, am I doing this page reload in the best possible way? I don't wanna risk knocking off any other parameters, although there are none others containing the phrase 'page'.
For example, is it best to check first if the page parameter is present in the URL (because sometimes it isn't in fact) and how would I do that?
Thanks.
The thing is RegExp is supposed to be used for patterns. And it will only work if the pattern matches. No you don't need to check if page exists before clearing it.
Related
I have a php $_SESSION passing the name of a target directory, that is different from situation to situation. I have a javascript function to execute a file with the same name but in several different directories, depending on the string passed with $_SESSION. My code is:
<?PHP
$where = $_SESSION["where"];
?>
<script>
var where = "<?php echo $where;?>";
function goToThere() {
document.location.href = where + "/file_to_execute.php";
}
</script>
<body>
<button class="buttongreen" onclick="goToThere()">proceed</button>
</body>
Say the content of $where is "dir_a". Then clicking on buttongreen might launch function goToThere, thus going to page "dir_a/file_to_execute.php". The problem is that the goToThere function simply does not do anything. I've tried different sequences to concatenate the variable and the string, with various combinations of quotation marks, without success.
What am I doing wrong?
As stated, your code is applicable to what you are trying to do. The issue lies in the "$_SESSION['where']"
Either...
(1) You have a forward slash at the end of $_SESSION['where'] and you are adding another forward slash when concatenating.
(2) You are not doing "session_start();"
(3) The script code is not being incorporated into the body nor header (I'm not quite sure about this, but as I see it, the script code really is in no man's land so maybe???)
(4) The $_SESSION['where'] is simply not being saved
(5) The $_SESSION['where'] is simply empty
As it stands though, your code is valid as a proof-of-concept for what you are aiming to do
I want to clear window.localStorage.clear after login and logout. I have added this code in the functions.php but it's not working. How can I overcome this?
add_action(' wp_logout ',' auto_redirect_external_after_logout ');
function auto_redirect_external_after_logout(){
echo '<script>window.localStorage.clear();</script>';
exit();
}
function do_anything() {
echo '<script>window.localStorage.clear();</script>';
}
add_action('wp_login', 'do_anything');
I think echo in PHP will only output the string but it won't execute the JS which is inside the string. Hence your localStorage is not getting cleared. Otherwise the syntax you wrote for clearing localStorage is right.
A bug in the sample code (which may be the only reason it's not working as desired) is the whitespace in the two string literals that are IDs:
add_action(' wp_logout ',' auto_redirect_external_after_logout ');
Should be
add_action('wp_logout', 'auto_redirect_external_after_logout');
The whitespace on the event name means your hook is attached to an event nobody's sending, and I'd expect the extra spaces around the function name to result in "registered function not found".
(I'm reading ./wp-includes/plugin.php and class-wp-hook.php, and it all flows to a call to php-builtin call_user_func().)
I have these two variables that I am trying to compare. They both have the same value, however, one is a href variable - meaning, it's being read from a file like this
<a href=http://google.com>Variable</a>
It's read like this, but displayed as an anchor tag in the browser, so when I go to compare a value using print "$collect_zids{$key} --> $temp";I see in the browser as
Variable --> Variable
How it appears in the browser. One text another link.
I'm assuming these two values are different hence why this code does not run
if($collect_zids{$key} eq $from_picture){
print "<h1>Hello</h1>";
}
Is there a way I can convert the href variable into a normal scalar variable so that I can compare them?
Thanks!
P.S. I think Javascript might be the only way, however, I don't have any experience with it.
There is no such thing as an "href variable". You have two scalar variables. One contains plain text and the other contains HTML. Your task is to extract the text inside the HTML <a> tag from the HTML variable and to compare that text with the text from the plain text variable.
One way to do that would be to remove the HTML from the HTML variable.
my $html = '<a href=http://google.com>Variable</a>';
my $text = 'Variable';
$html =~ s/<.+?>//g;
if ($html eq $text) {
say "Equal";
} else {
say "Not Equal [$html/$text]";
}
But it cannot be emphasised enough that parsing HTML using a regular expression is very fragile and is guaranteed not to work in many cases. Far better to use a real HTML parser. HTML::Strip is made for this very purpose.
#!/usr/bin/perl
use strict;
use warnings;
use feature 'say';
use HTML::Strip;
my $html = '<a href=http://google.com>Variable</a>';
my $text = 'Variable';
my $parser = HTML::Strip->new;
$html = $parser->parse($html);
if ($html eq $text) {
say "Equal";
} else {
say "Not Equal [$html/$text]";
}
It's also worth pointing out that this is answered in the Perl FAQ
How do I remove HTML from a string?
Use HTML::Strip, or HTML::FormatText which not only removes HTML but
also attempts to do a little simple formatting of the resulting plain
text.
Update: In a comment, you say
I have no way of using these methods since I am not explicitly defining the variable.
Which is clearly not true. How a variable is initialised has no bearing whatsoever on how you can use it.
I assume your HTML text is in the variable $from_picture, so you would strip the HTML with code like this:
my $parser = HTML::Strip->new;
my $stripped = $parser->parse($from_picture);
if($collect_zids{$key} eq $stripped){
print "<h1>Hello</h1>";
}
I have no idea where you got the idea that you couldn't use my solution because I was directly initialising the variables, where you were reading the data from a file. An important skill in programming is the ability to see through complex situations and extract the relevant details. It appears you need to do some more work in this area :-)
I found the answer using the Perl module HTML::FormatText;
use HTML::FormatText;
my $formatter = HTML::FormatText->new();
my $string = HTML::FormatText->format_file("path_to_the_file"); #$string variable to hold the result and the path must be for a file.
After using the HTML::FormatText module, I was able to get the raw string that was being read, instead of it being interpreted as HTML. So, I was getting <a href=http://google.com>Variable</a> returned, instead of just Variable. After getting the raw string, I could use regex to extract the parts that I needed.
Credit to - https://metacpan.org/pod/HTML::FormatText
I am using the javascript below to send information from one website to another, but I don't know how to add more data. ?url is fine. I'm not sure how to add more data to the javascript. I would like to add an ?img, a ?title ... i tried a few times but no luck. Help please.
JavaScript
onclick="window.open('http://mysite.com/submit.?url='+(document.location.href));return false;"
PHP
$url = $_GET['url'];
Separate the parameters with &.
http://mysite.com/submit?param1=value1¶m2=value2¶m3=value3
You should also encode your values with encodeURI().
You wouldn't add ?moreParm...etc, you use an ampersand (&) to add additional parameters.
var url = `http://mysite.com/submit.?url=' + document.location.href;
url += '&anotherParam=foo`;
// etc.
You need to escape all parameter values accordingly.
I'd also recommend moving it into a function so your embedded JS doesn't become impossible to read.
I use the following javascript class to pull variables out of a query string:
getUrlVars : function() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
So this works: http://example.com/signinup.html?opt=login
I need http://www.example.com/login/ to work the same way. Using mod_rewrite:
RewriteRule ^login/? signinup.html?opt=login [QSA]
allows the page to load, the javascript to load, the css to load, but my javascript functions can't find the opt key (i.e., it's undefined). How do I get opt to my javascript?
Javascript is client-side. Mod_rewrite is server-side.
Therefore Javascript will never see the rewritten URL. As far as your browser is concerned, the URL that you entered is the finished address.
The only real solution is to change your Javascript so it looks at the URL it's got rather than the old version (or possibly parse for both alternatives, since the old URL will still work and people may still have old bookmarks).
The other possible solution would be to go to your server-side code (PHP? whatever?) where you can see the rewritten URL, and insert some javascript code there which you can parse on the client side. Not an ideal solution though. You'd be better of just going with option 1 and changing you Javascript to cope with the URLs it's actually going to be getting.
Your issue is that JavaScript runs on the client side, so it will never see the ?opt=login part to which the URL gets converted internally on the server.
Apart from changing your regular expression to match the new URL format, the easiest workaround might be to write a JavaScript statement on server side that introduces the value of the opt variable into JavaScript.
If you're using PHP, you can have the PHP create a JavaScript variable for you. For example:
$params = "?";
foreach($_GET as $key => $value) {
$params = $params . $key . "=" . $value . "&";
}
echo 'var urlParams = "' . $params . '"';
Now, you JavaScript will have access to a urlParams variable that looks like this
?opt=login&
Then, in your Javascript code, wherever you expected to use the URL parameters, use the urlParams instead.
If it's a special case, then put it as a special case in some way. If you rewrite generally, change your general regular expression. The way mod_rewrite works, the client never knows the rewritten URL. From the client, it's /login/ and /login/ only. Only the server ever knows that it's really signinup.html?opt=login. So there's no way your regular expression or location.href can know about it.
Unless you use the [R] flag in your RewriteRule, the browser (and thus javascript) will never know about the new URL. If you don't want to be redirecting people, you're going to have to add some code to your login page that GET parameters as javascript in the page.