localStorage.clear not working properly in Wp - javascript

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().)

Related

How to concatenate a variable in a document.location.href path?

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

Passing PHP array to Javascript w/o showing up in source

I'm working on a historical database with 2,000+ photos that need to be categorized of which about 250 are loaded. I've created a MYSQL database with 26 fields to hold this data.
I'm using PHP to access the database and retrieve the information.
I'd like to use JavaScript to manage the rest of the form. All of the code is in one php file.
The problem I'm running into is when I
//$result is the php associative array holding the photo information
<div id="dom-target" style="display: none;">
<?php echo json_encode($result); ?>
</div>
<script>
var div =document.getElementById("dom-target");
var photo_array = JSON.parse(div.textContent);
It works but, I get the entire database structure and data embedded in the source html output. Obviously this won't do especially as the photo count increases.
How can I prevent this?
If I were to split this one php file into two, one containing php accessing the database and returning an array, and the other page containing all of the input boxes etc., and use AJAX passing the array as a JSON; would that work? I'd hate to go down that path unless it'll be successful. I've read where you can't pass the array if all of the code is on one page.
Or, should I just stick with doing everything in php?
Thanks, Eric
Edit: What I want to do is to pass a php array to js without having all of the data in the array included in the source. By source I mean when someone "views source". I also think that once I get up to 2,000 photos is is going to be unwieldy....(2,000 photos) x (26 fields) = a lot of stuff needlessly included in the web page.
I have no objection to using AJAX. But all of the examples I've seen have the request on one page and the response on another. Do I need to split up my code onto two pages; one to handle the php and MySQL and the other to handle the html and js?
What I envision is a screen showing the selected photo at 800x600 with the input fields below that. A person enters the title, caption, description etc and that is saved in the db with the photo's name. Below that I would have 20 thumbnail photos which a person could pick from to enter that photo's information. I would loop through the database 20 or so, photos at a time. Only the file names are stored in the database, the actual photo jpg is stored on a hard disk and retrieved via an statement.
How can I do this without all of the data in the database array being on the html source page?
Edit 2: I've been asked to include more of my php. Sorry I couldn't make it neater.
<?php
$stmt_select->bind_result(
$select_array['fhs_pkey'],
$select_array['file_name'],
$select_array['caption'],
$select_array'post'],
$select_array['photo_type'],
$select_array['last_name'],
$select_array['first_name'],
$select_array['middle_name'],
$select_array['honorific'],
etc., etc., etc
);
// put all of the database info into an array. Filename field is for full size photos
$j=$stmt_select->num_rows;
for ($i=0;$i<$j;$i++)
{
$stmt_select->data_seek($i);
$row = $stmt_select->fetch();
//put all of the column data into the array
foreach ($select_array as $key=>$value)
$result[$i][$key]=$value;
//in a separate php file resize the photos and save them
//put full path with appended filename to retrieve later
$result[$i]['resized'] =
"../images/fhs_images/800x600_photos/800x600--" .
$result[$i]['file_name'] ;
$result[$i]['thumb'] = "../images/fhs_images/200x150_photos/200x150--" .
$result[$i]['file_name'] ;
}
$stmt_select->close();
$stmt_update->close();
$stmt = null;
$conn = null;
echo '<figure id="photo_figure">';
$filename = $result[2]['resized'];
echo "<img src = "."'".$filename."'" ."/>";
?>
<script>
//below is where I get the entire array printed out when I view source
var photo_array = <?php echo json_encode($result); ?>
var testing = photo_array[40]['thumb'];
//take care of spaces in filenames
testing = encodeURI(testing)
document.write('<img src=' + testing + '>')
</script>
Edit 3 #trincot
Something's not right. I moved all of my MYSQL db setup and retrieve into a new file called fhs_get_photos.php. In my jQuery ready function I added the below. See my comments on what gets displayed
var myarray;
$(document).ready(function()
{
$('.tooltips').powerTip();
$(".radio1").on('click',(function()
{
var photo_type = $("input[name='photo_type']:radio:checked").val();
if(photo_type == 2)
$(".person").hide();
else
$(".person").show();
}));
$.getJSON("fhs_get_photos.php", function(photo_array)
{
if (photo_array.jsonError !== undefined)
{
alert('An error occurred: ' + photo_array.error);
return;
}
// photo_array now contains your array.
// No need to decode, jQuery has already done it for you.
// Process it (just an example)
//$.each(photo_array, function(i, obj){
// $("#dom-target").append(obj.fhs_pkey + " " + obj.file_name + ", ");
//this displays correctly on a screen but not with anything else.
//Seems as if it's rewriting the page and only this is displaying which
//may be how it's supposed to go
document.write("In js. photo_array 2,caption is: " + photo_array[2] ['caption']);
});
});
In my main php I put
document.write("photo_array 2,caption is: " + photo_array[2]['caption']);
but it's not displaying anything. I suspect photo_array is not being passed into the page. In the js file, I then created a global variable 'myarray' and in the .getJason function I added
myarray = photo_array;
thinking it would pass into the main file but it didn't.
There are in principle two ways you can think of to get data in JavaScript:
1. Ajax request
With this solution use your current PHP file for generating the HTML page only, so without generating JSON, and create another PHP file which will generate the JSON only.
So let's say your JSON-generating PHP file is called fhs_get_photos.php, then it would have this code (no HTML!):
<?php
header("Content-Type: application/json");
// Collect what you need in the $result variable.
// ...
// and then:
echo json_encode($result);
?>
See the last section in my answer for treating JSON encoding errors.
Make sure there are no line breaks or spaces before the opening <?php, and that you do not echo or print anything else than that one JSON string.
Your database query would also be in this new file. Note that currently you have a mix, like with this line:
echo "<img src = "."'".$filename."'" ."/>";
This line belongs in the non-JSON file, but it also depends on the query. So either you make an include file that does the query, include it in both PHP files, or you move the logic of defining the image tag (or at least the image's source) to the JavaScript part (better!).
Then in the original PHP file, remove the JSON output, and add some JavaScript, using jQuery (I understood you were already using it, so you have it included):
$(function(){
$.getJSON("fhs_get_photos.php", function(photo_array){
// photo_array now contains your array.
// No need to decode, jQuery has already done it for you.
// Process it (just an example)
$.each(photo_array, function(i, obj){
$("#dom-target").append(obj['fhs_pkey'] + " " + obj['file_name'] + ", ");
});
// or things like:
$("#caption_input").val(photo_array[2]['caption']);
});
});
This function will get executed once the HTML DOM has been built, so evidently after the first PHP file has finished execution. It will make the request to the second PHP file. Once that request is answered by PHP, the inner call-back function will receive the data. Note that there is no need to decode JSON here, as jQuery has already done that for you.
2. Generate JavaScript with data
Here you keep your current PHP file, but move the part where you inject the JSON encoded data to the JavaScript block:
<script>
var photo_array = <?php echo json_encode($result); ?>;
// ... process it
</script>
There is no need to wrap JSON in a JavaScript string to then parse it.
From json.org:
JSON is a subset of the object literal notation of JavaScript. Since JSON is a subset of JavaScript, it can be used in the language with no muss or fuss.
2.1. Valid JSON that could be invalid JavaScript?
Although not a problem in the context of this question (see below), there is an incompatibility between JSON and JavaScript syntax. It concerns whether or not the non-ASCII characters U+2028 LINE SEPARATOR and U+2029 PARAGRAPH SEPARATOR are allowed to appear unescaped in quoted strings:
JSON syntax allows this, as stated in the ECMAScript® 2015 Language Specification, section 24.3.1:
JSON allows Unicode code points U+2028 and U+2029 to directly appear in String literals without using an escape sequence.
JavaScript syntax does not allow this, as indicated in the ECMAScript® 2015 Language Specification, section 11.8.4:
All code points may appear literally in a string literal except for the closing quote code points, U+005C (REVERSE SOLIDUS), U+000D (CARRIAGE RETURN), U+2028 (LINE SEPARATOR), U+2029 (PARAGRAPH SEPARATOR), and U+000A (LINE FEED). Any code points may appear in the form of an escape sequence.
PHP's json_encode however, follows the possibility offered in that last line, and escapes all non-ASCII characters, including the problematic U+2028 and U+2028, except if you explicitly tell PHP not to do so with the JSON_UNESCAPED_UNICODE flag:
JSON_UNESCAPED_UNICODE (integer)
Encode multibyte Unicode characters literally (default is to escape as \uXXXX). Available since PHP 5.4.0.
So, a json_encode call without this flag will not produce instances of this problem.
3. Catch json_encode failures
According to the manual on json_encode the method can return a non-string (false):
Returns a JSON encoded string on success or FALSE on failure.
When this happens echo json_encode($result) will output the empty string, which is invalid JSON.
This error condition should be captured in PHP, for example like this:
<?php
header("Content-Type: application/json");
// Collect what you need in the $result variable.
// ...
// and then:
$json = json_encode($result);
if ($json === false) {
$json = json_encode(array("jsonError", json_last_error_msg()));
if ($json === false) {
// This should not happen, but we go all the way now:
$json = '{"jsonError": "unknown"}';
}
}
?>
And then in JavaScript, this condition should be handled as well, for example like this:
if (photo_array.jsonError !== undefined) {
alert('An error occurred: ' + photo_array.jsonError);
return;
}

taking unset() and rewriting this function in javascript

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.

assigning php return value to a javascript variable

I have a database form on a MySql table on which I have a javascript function to populate the options of a select tag. Those options are fetched from a table of clients who have a status of either "Active" or "Inactive", and the return values are of those clients where their status is active. In the event an order is loaded where the client status is inactive, I'm trying to add a handler for inactive clients. The form loads from a php script that left joins the client table to the main table, where clientId in the main table is equal to Id in the client table. So, I have the name and id of the client fetched outside of the function to populate the options list, regardless of their status.
There is one line that is causing me fits. I have searched this site and others and have found many solutions, but none have worked for me so far. This is the line:
var txt = <?php echo $row[`clients`.'name']; ?> ;
What is returned in Chrome and Firefox debuggers is, "Uncaught syntax error: Unexpected token <". The debugger shows: var txt = <br />
I've tried enclosing the php script in single quotes, double quotes, and without quotes, and still no luck. Any thoughts, anyone?
About an hour later--> I found a workaround. I tried all of your suggestions, but none worked in this instance. var_dump and json_encode confirmed what I knew already, that the returned data was valid. Regardless of any of the variations in syntax, they all returned the same error. What I did was to apply the same syntax as above, but in a hidden input:
<input type="text" id="cName" hidden value="<?php echo $row[`clients`.'name']?>" />
Then changed the javascript code to this:
var txt = document.getElementById('cName').value;
Everything else works perfectly. Of course, I still have lingering thoughts about the use of backticks, and would prefer that I had a better, and safer code. As I mentioned somewhere, I simply copied the sql syntax directly from phpMyAdmin. In this instance, if I substitute single quotes for the backticks, the input returns nothing. Well, thanks all. If anyone wants to contribute more, I'll be glad to hear about it.
That's illegal PHP syntax, and very dangerous syntax in general. Try doing a var_dump($row) to see exactly what's in that array. Probably you want something more like
var txt = <?php echo json_encode($row['clients.name']); ?>;
instead.
Note the use of json_encode(). This will ENSURE that whatever you're spitting out in the JS code block is actually syntactically valid javascript.
e.g. consider what'd happen if you ended up with
var txt = Miles O'Brien;
^^^^^--undefined variable;
^--- another undefined var
^--- start of a string
^^^^^^^---unterminated string.
with json_encode(), you end up with
var txt = "Miles O'Brien";
and everything's a-ok.
var txt = "<?php echo $row['clients']['name']; ?>";
var txt = <?php echo $row[`clients`.'name']; ?> ;
Consider how PHP parses this:
var txt = is to be output directly to the client.
Enter PHP mode.
echo the following expression.
Evaluate $row[`clients`.'name'].
First we need to determine the array index, which is the concatenation of `clients` and 'name'.
Backtick in PHP is the execution operator, identical to shell_exec(). So PHP attempts to execute the shell command clients, which probably fails because that isn't what you intended and it doesn't exist. Consequently, at this stage, PHP outputs an HTML error message, starting with a line break <br />.
Your client now has var txt = <br /> (you can verify this by inspecting the HTML source of the page returned to your browser), which it attempts to evaluate in its JavaScript context. This gives rise to the "unexpected token" error that you have witnessed.
As others have mentioned, you probably meant to do something like $row['clients']['name'] or $row['clients.name'] instead—but without seeing the rest of your PHP, it's impossible to be sure. Also, as #MarcB has observed, you need to be certain that the resulting output is valid JavaScript and may wish to use a function like json_encode() to suitably escape the value.
The error comes from the fact that your return value (a string in javascript) must be in quotes.
Single quotes will take whatever is between them literally, escapes (like \n ) will not be interpreted, with double quotes they will.
var txt = "<?php echo $row['clients']['name']; ?>";
is what you want
Change this
var txt = <?php echo $row['clients'.'name']; ?> ;
to this:
var txt = <?php echo $row['clients']['name']; ?> ;

Storing HTML in a Javascript Variable

I am currently coding a website that will allow a user to input data into a MySQL database using a WYSIWYG editor. The data stores into the database without a problem and I can query it using PHP and display it on my webpage.
Up to this point everything is working ok until I try to move the HTML stored in the MySQL database into a javascript variable. I was able to get it working using CDATA[], but not for every browser. It works in Firefox, but not IE or Chrome. I am looking for a solution that will be able to work in all of the browsers. Any help would be greatly appreciated.
Since you're using PHP:
<script>
var foo = <?php echo json_encode($htmlFromDatabase); ?>
</script>
The json_encode method, while normally used for encoding JSON objects, is also useful for converting other PHP variables (like strings) to their JavaScript equivalents.
"Safefy" your code, like this
str_replace( array("\r", "\r\n", "\n", "\t"), '', str_replace('"','\"',$str));
The above function clears linebreaks, and tabs so that your code appears in one line. If it breaks into more than one line, then it cannot be parsed as a string in JS and an error is thrown. Also we are escaping " to \", maybe there are more string replacements that need to take place, it depends in your content.
and inline it in javascript,
//<![CDATA[
var myHtml = <?php echo '"'.$stuff.'"'; ?>;
//]]>
keep in mind the '"' part so that it appears like this var myHtml = "test";

Categories