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

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

Related

localStorage.clear not working properly in Wp

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

Unterminated string literal with PHP in JavaScript

Please tell me why this code tells me
SyntaxError: unterminated string literal
My code:
<script>
console.log(" <?php $geladen = file_get_contents("./testtext"); echo $geladen; ?> ");
</script>
That's a JavaScript error message, which strongly implies one of two things:
the JavaScript that reaches the browser still includes the <?php etc., meaning the PHP didn't get parsed on the server (and thus the browser flipped out on "./testtext"), or
the file testtext (and therefore your variable $geladen) contains quotation marks. Either is possible from the very little information you have posted.
You can figure out which it is by looking at the HTML in your browser.
If it's the former (if you see <?php in the HTML), then you need to fix your server configuration.
If it's the latter (if testtext contains any " marks), then you need to encode it properly before echoing, using json_encode() like this:
<script>
console.log(" <?php $geladen = file_get_contents("./testtext"); echo json_encode($geladen); ?> ");
</script>
All that said, mixing PHP and HTML (not to mention PHP, HTML, and JavaScript) this way is not a great practice. You'd be much better off using a templating engine of some sort (Twig, Blade, etc.).
If the contents of 'testtext' contains a quote mark, it will break the javascript. Try addslashes().
<script>
console.log(" <?php $geladen = addslashes(file_get_contents("./testtext")); echo $geladen; ?> ");
</script>

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.

Extracting inline javascript var in html source to a PHP array

There is some data that I need to get from a local crawled page. It's inline javascript like this:
<script type="text/javascript">
//<![CDATA[
var graph_data = {"query":{"cid":["13908"],"timestamp_from":1402531200,"timestamp_till":1402531200,"views":1138942,"data":
etc, the variable is very long but you get the idea. I want to put "graph_data" into an array called $data. What is the best way to do this? I should add this is all being done by me locally & I don't need to execute any javascript code, just extract the data.
I have make a suggestion purely as an idea with some code worth trying!
As suggested, the DOM Document may provide this much easier, but here's another possible solution for extracting...
I'm guessing that the var graph_data is a JSON string that you want to extract from the HTML page so that you can store as a PHP var. The problem is that your code doesn't show how the variable ends but I'm going to assume that a new line break would be the way to identify the end of the variable being set. It may be a semi-colon though and if it is, instead of "\r\n" try ";"
// Assuming your html code is stored in $html...
preg_match("/var graph_data[^\{]*?(\{[^\r\n]+?)/is",$html,$match);
print "<pre>";
print_r($match);
print "</pre>";
This should result in $match[1] storing the part you need.
You can try passing that into json_decode() but that's touching some wood with crossed fingers.
Good luck...

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']; ?> ;

Categories