Call Javascript Date Code Into PHP Buffer - javascript

ISSUE:
I am attempting to call a JavaScript 'date_code' file (to get current YYYY/MM) to use as part of my 'directory URL' to store some .php files.
EXAMPLE:
"../Directory/2017/07.php" would represent the .php 'directory' file for the month of July, 2017.
NOTE:
A similar process works successfully if I am using it within a 'form submission'...
However, in this particular case, I am constructing a Cron Job, so a form will not be part of the process.
ATTEMPTS:
Among other things, I have attempted to use...
<?php $dateIndex = "path_to_date_code.js"; ?>
(as shown in the demo code below).
RESULTS:
So far... I have had no success at all being able to call in the JavaScript 'date code' or output the files to their proper destination.
SUMMARY:
If anyone could advise me what I am doing wrong or point me in the right direction, I would greatly appreciate it. Thank you in advance.
DEMO:
<?php ob_start(); ?>
<html>
<head>
</head>
<body>
<?php echo "Some Content" ?>
<?php $dateIndex = "path_to_date_code.js"; ?>
</body>
</html>
<?php echo ''; file_put_contents("../Directory/$dateIndex.php", ob_get_contents()); ?>

You are confusing the roles of PHP and Javascript. PHP runs on the server, while Javascript and your date code file only run IN THE BROWSER. The Javascript will do nothing on the server.
I don't really understand what you are trying to do, but how about constructing a path like this:
$date = date("Y/m"); // Y is 4 digit year, m is two digit month
$path = "../Directory/{$date}.php";
The braces are not really needed. They are used to isolate a variable when embedded in a string. I've added them so the variable stands out.
If you need to make a path for a given date, use this type of thing:
$date_to_use = "2015-12-12"; // whatever
$date = date("Y/m", strtotime($date_to_use));
$path = "../Directory/{$date}.php";

Related

Lost formatting for a price when bypassing jQuery

I am trying to modify a Monero payment gateway extension for Wordpress/WooCommerce so that it prints some basic payment information as normal HTML, beyond just rendering it with jQuery. It is important that this code works Javascript free. I have modified the template where this information displays so that there are <noscript> elements which contain the following...
<?php echo $details['amount_total_formatted']; ?>
That is an example of one element but there are a few others in the template. The issue is when I test this the output is formatted incorrectly.
The output appears like this 714229029442 and not as 0.714229029442 like when Javascript renders the output.
Here is a snippet of this array being created in the method which includes the template I am modifying...
$details = array(
...
'amount_total' => $amount_total,
'amount_total_formatted' => self::format_monero($amount_total),
...
);
Here is the body of the format_monero method and the defines it uses...
define('MONERO_GATEWAY_ATOMIC_UNITS', 12);
define('MONERO_GATEWAY_ATOMIC_UNITS_POW', pow(10, MONERO_GATEWAY_ATOMIC_UNITS));
define('MONERO_GATEWAY_ATOMIC_UNITS_SPRINTF', '%.'.MONERO_GATEWAY_ATOMIC_UNITS.'f');
public static function format_monero($atomic_units) {
return sprintf(MONERO_GATEWAY_ATOMIC_UNITS_SPRINTF, $atomic_units / MONERO_GATEWAY_ATOMIC_UNITS_POW);
}
The template file I am working on has the below JS code which assigns variables within using JSON and also gives it AJAX support. It does$details_json = json_encode($details) before including the JS.
<script type="text/javascript">
var monero_show_qr = <?php echo $show_qr ? 'true' : 'false'; ?>;
var monero_ajax_url = '<?php echo $ajax_url; ?>';
var monero_explorer_url = '<?php echo MONERO_GATEWAY_EXPLORER_URL; ?>';
var monero_details = <?php echo $details_json; ?>;
</script>
When using the Javascript and using the developer tools there is a variable called amount_total_formatted defined within which is formatted properly with the decimal place.
I want to format the XMR price in my PHP within the template with the proper formatting including the decimal place, and I want to keep changes to the template that do it as simple as possible. I admit I do not really understand the format_monero method used to do some kind of formatting or what jQuery does once being passed that value.

How to pass a php variable from a php file to js file? [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 6 years ago.
I have an html/php composite document that uses the login variable from a user. (This came from a separate php file on signin):
<html> Welcome <?php echo $login; ?> </html>
//Now when the user uses the chatbox, and clicks send, I would like to pass the data (inclusive of the username) from this html file to the .js so it can in turn pass onto another php file. (ps I tried the following but to no avail, as the .js file is external to the html/php composite):
$("#newMsgSend").click(function()//triggers script to send the message
{
$("#newMsgCnt").val(''); // clears the box when the user sends a message
var username = "<?php echo $login; ?>";
alert(username);
});
Your current code is likely introducing an XSS vulnerability. Instead, take advantage of the fact that valid JSON is valid JavaScript:
var username = <?php echo json_encode($login); ?>;
In some situations, it may also be better to use an XMLHttpRequest or WebSocket that requests the data from another URL (typically encoded as plain text, XML or JSON). One scenario for that would be notifying the user once new items have been added after the user loaded the webpage.
when the user logs in, create a session for that user and populate it with the data (such as username, email, phone number or whatever) from the database - as followings (assuming that the login is correct and authentic:
$_SESSION['user'] = $row; //where $row is the row of data returned from the db
Then whenever you want to access that information include the following at the top of the page:
session_start();
and then access the information such as
$userfirst_name=$_SESSION['user']['first_name'];
then your html will be something like:
<h1> Welcome <?php echo "$userfirst_name"; ?> </h1>
note that session start must be at the top of each page you are wanting to access the sessiobn variables. Then to clear the user details (such as when the user logs out you can use the following:
unset($_SESSION["user"]);
Thanks to both: Ivan Rodriguez Torres and phihag. I got a solution somewhere in the middle of both posts:
<input id="login" readonly type="text" <?PHP echo "value= '$login'/>"; ?>
Ivan's suggestion was somehow returning an "undefined" variable for me. The above works like a charm though. Hope its safe and doesnt lead to any problems.
Thanks again guys

passing php variable to separate javascript file

I have been reading how to pass variables from a php webpage to a separate javascript file, but am not having any luck.
Please don't mark this as duplicate, as I know there are a ton of things out there telling the ways to do this. I recognize those posts and am more just checking my syntax or seeing if there is anything unique about my specific situation that is causing those methods not to work.
So I have a PHP webpage where I POSTed some variables to:
DOCTYPE HTML
...
<?php
$id = $_POST["id"];
$name = $_POST["name"];
?>
...
HTML code with some usage of PHP variables
javascriptFunction()
end page
Then in a separate javascript file I have:
var markerlocation = '<?php echo $point; ?>';
function javascriptFunction () {
alert("markerlocation");
});
This seems really straight forward, but for whatever reason I can't get it. I also have tried with json encode.
I can delete this when done.
Sincere thanks for any help.
My way:
Declare a Array to store variable for passing variable to JavaScript
Encode the Array to JSON in php
Decode the JSON String from php and store as a JavaScript variable
PHP
<?php
//You may declare array for javascript
$jsVal = array(
'user_name' => 'Peter',
'email' => 'peter#gmail.com',
'marker_location' => '102,300'
);
?>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>var phpConfig = jQuery.parseJSON(<?=json_encode($jsVal)?>);</script>
Separated javascript file
alert(phpConfig.marker_location);
You can try it
You can point the script tag source to a .php file instead of a .js file, I think that's what you want. Works with image tags too ;)
Edit: some browsers may require the text/javascript mime header in order for it to work properly, but it's not hard with PHP I'll assume you already know how to do that.
On a side note: This option should probably only be used if you're planning on allowing the client to cache the javascript output. If you don't want the client to cache it, you need to set additional headers.

Dynamic posts loading with javascript and php

I've been trying to make a blog system but I've got lost at some point. The posts get generated in this format: posts/today/today.xml (for example: posts/2014-08-19/2014-08-19.xml) The xml contains the image's name, the title and the date when it was made. It's okay if I want to load today's posts, there's no problem with that but the main problem is about the posts loading which are older than a day.
I've got a function in ajax which loads the xml the only parameter it needs is the url to the xml. Let's call it loadPost(url).
I made the formatting purposely so I'd like to keep that.
I couldn't find a way to load it dynamically with php because after the php brackets are executed the variables delete right ? Or shall I use global variables ?
Now it looks like this:
<script type="text/javascript" language="javascript">
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() > $(document).height() - 100) {
loadPost('posts/<?php echo $nextpost.'/'.$nextpost ?>.xml');
<?php
$nextpost = date ('Y-m-d',strtotime( '-1 day' , strtotime ($nextpost)));
echo $nextpost;
?>
}
});
</script>
I'm in really need for help, anybody got an idea how to go on ?
Thanks in advance !
EDIT:
This is called in the first few lines in index.php
<?php
session_start();
$_SESSION['dayCounter'] = 0;
$today = date("Y-m-d", time());
$nextpost = date ('Y-m-d',strtotime( '-1 day' , strtotime ($today)));
?>

How can I edit a portion of a URL and reload the new page

Evening all.
This is the first post I've made on here, so I hope I get this right.
I've looked everywhere (both on this site, and elsewhere), for a solution to an issue I'm having, but I can't find anything which sounds like my issue, yet I know logically it should be doable!
I maintain two intranet sites - one English and one Welsh. They are mirrors of each other, only the domain and site name change:
Example
http://english-site/news/item/003/170314.htm
http://welsh-site/newyddion/item/003/170314.htm
So far, I've only found this: http://www.codingforums.com/javascript-programming/8523-how-do-i-switch-pages-automatically.html
Which gave me some hope, but I can't work out how to apply it to my situation.
So, the question is this - is there a way to edit and reload the hyperlink switching out this:
english-site/news/
For this:
welsh-site/newyddion/
But keeping the rest of the link the same so the page will load with the Welsh or English equivalent of its self.
I know most modern CMS's could do this kind of thing automatically...but I'm not using a modern CMS...I'm using FrontPage...I'm certain this is possible but cant find anywhere that agrees with me!
Cheers in advance for any help anyone can offer!
FrontPage is ancient and you really shouldn't use it.
That being said, this bit of JS should do what you want:
window.location.href = "http://welsh-site/newyddion" + window.location.pathname.substring(window.location.pathname.indexOf('/', 1));
The current page's path (everything that follows the domain name) is accessible using window.location.pathname. Using indexOf('/', 1) on this gives us the position in the string (starting at 0) of the first / character (we pass 1 as the second parameter so as to ignore the starting slash). We then use substring to get everything from that character on.
Finally, we set the new URL to window.location.href, which performs a redirect.
You could possibly do this using regex, but this works just as well.
I am assuming your page has a button/link/select event which triggers which domain you want to serve from saying English or Welsh. Given this condition, you can do a simple javascript replace shown below :
if (selection === "blah blah"){
domain = "http://domainA...";
} else {
domain = "http://domainB...";
}
window.location.replace(domain);
reference
I wouldn't recommend having urls generated with javascript, but rather links on each of the page to the corresponding translated page using rel="alternative" and hreflang="code" with the language code corresponding to the 2 letter language code standard as depicted in http://googlewebmastercentral.blogspot.mx/2010/09/unifying-content-under-multilingual.html
to instruct the bots the pages are the same content in different languages.
If you could use a bit of php or server side code you could create your link reference very easily by replacing the urls with the new urls you are trying to create out of the current url. This is done by using patterns that perfectly match your criteria of url rewriting, that said, if you dont have any pattern, the best would be to set each link url separate per page.
Lets say you only need to convert english-site domain to welsh-site and news path segment to. According to http://reference.sitepoint.com/html/lang-codes, Welsh lang 2 letter standard would be 'cy'.
<?php
$lang['cy']['domain'] = 'welsh-site';
$lang['cy']['lang'] = 'Welsh';
$lang['cy']['news_slug'] = 'newyddion';
$lang['en']['domain'] = 'english-site';
$lang['en']['lang'] = 'English';
$lang['en']['news_slug'] = 'news';
$lang['default'] = 'en';
Explanation:
We are defining an array of languages where we will setup anything we need to translate. This is a multidimensional array map that defines each language by key in the first dimension, then each segment to translate in the second dimension. In this second dimansion we will setup special keys ending in _slug which will be part of the url to translate. This array can be saved in a special file apart for anything else and where we can go and edit easily without having us to modify the core code.
After defineyour initial language settings, now you need the code to identify the current language and path:
<?php
include('lang.php'); //this is the file where the language array is defined
$path = $_SERVER['REQUEST_URI'];
$host = isset($_SERVER['HTTP_HOST']) ? substr($_SERVER['HTTP_HOST'], 0, strpos($_SERVER['HTTP_HOST'], ':')) : $_SERVER['SERVER_NAME'];
foreach ($lang as $code => $l) {
if ($l['domain'] == $host) {
$current_lang = $code;
break;
}
}
if ( ! isset($current_lang)) {
$current_lang = $lang['default'];
}
$_ = $lang[$current_lang];
$segment_1 = reset(explode('/', trim($path, '/'));
foreach ($lang[$current_lang] as $section => $url_segment) {
if ($segment_1 == $url_segment && substr($section, -5) == '_slug')
$current_section = $section;
break;
}
}
Explanation:
This code works as a bridge code that obtains the current section and language. First we obtain the host (domain name) and url path. In the first loop we match against any language domain to find the correct language we are on, then in the second loop we try to find the current section we are on with respect to the current language.
Now a little code to write the links using known information :
<head>
<?php foreach ($lang as $code => $l): ?><?php if ($code != $current_lang) : ?>
<?php $lang_path = isset($current_section) ? str_replace('/' . $_[$current_section] . '/', '/' . $l[$current_section] . '/', $path) : $path; ?>
<?php $lang_url = '//' . $l['domain'] . $lang_path; ?>
<link rel="alternative" hreflang="<?php echo $code; ?>" href="<?php echo $lang_url; ?>">
<?php endif; ?><?php endforeach; ?>
</head>
Explanation:
We are adding links that will tell bots the other links in your page are just different representations of this page in a different language. We also specify the lang code inside hreflang attribute (http://googlewebmastercentral.blogspot.mx/2010/09/unifying-content-under-multilingual.html)
Then you create your links (in the body section somewhere) the exact same way:
<ul>
<?php foreach ($lang as $code => $l): ?>
<?php if ($code != $current_lang) : ?>
<?php $lang_path = isset($current_section) ? str_replace('/' . $_[$current_section] . '/', '/' . $l[$current_section] . '/', $path) : $path; ?>
<?php $lang_url = '//' . $l['domain'] . $lang_path; ?>
<li><?php echo $l['lang']; ?></li>
<?php else : ?>
<li class="active"><?php echo $l['lang']; ?></li>
<?php endif; ?>
<?php endforeach; ?>
</ul>
For all this to work your server must support PHP extension. I used php code because this is the most common code support to find.
You also need to change your file extensions, from .html to .php for this to work.
Hope it works for you. This might not be what you wanted, but rather what you actually need.

Categories