I have a php code as shown below in which there is an if condition.
php:
if(mysqli_num_rows($result1) > 0){ // Line X
while($row = mysqli_fetch_array($result1)){
if($row['open'] == "true") {
if(!isset($_SESSION['admin'])) {
$message = "user " . $row['user_name'] . " is currently editing the form. Want to take over ?"; // Line B
echo "<script type='text/javascript'>if(confirm('$message')) { } else { };</script>"; // Line A
}
break;
}
}
}
I was able to integrate $message at Line B.
I am wondering what changes I should do at Line A so that I can integrate the following code in the curly braces of the if(confirm('$message') block:
$username = $_SESSION['user_name'];
$open="true";
$write="1";
$stmt=$connect->prepare("UPDATE trace_users SET write=0 WHERE write=1"); // revoke write access of all users
$stmt=$connect->prepare("UPDATE trace_users SET open=?, write=? WHERE user_name=?");
$stmt->bind_param('sss', $open, $write, $username);
$stmt->execute();
Unfortunately user1950349, this is a bit more complex than it may seem because your idea is closer to how a desktop app would where there is a message loop which allows the code to respond to user input. But with a webpage generated by php and sent over the internet, we do not have a message loop to work with. Thus, we have figure out a way to get the server and the user's computer to message back and forth without any additional webpage loads.
This is where AJAX would come into play; however, an explanation of how to use that for your use case would depend on how you implement AJAX. For instance, you might use jQuery or some other javascript library.
It is a good practice if you avoid mixing two different languages together.
When mixing these two the complexity of your code increases.
Since you need the answer here you go
echo "<script type='text/javascript'>if(confirm(" . $message . ")) { } else { };</script>";
Inside echo's double/single quotes(" / ') everything is considered as a string, so to access your PHP variable you need to use the concatenation method to use that PHP variable.
if(confirm(" . $message . "))
UPDATE
You need to follow the same steps, as described above. You need to use the string concatenations.
But that will be very complex and as well as very difficult to make debugging.
You can use a better approach using XHR request or you can design the PHP code in a better way to use it with your JavaScript code.
Related
I apologize if my question title is at all confusing, this is my first post and despite reading https://stackoverflow.com/help/on-topic I feel like I may still have some flaws in my question-writing abilities.
TL;DR: JavaScript animation works if I do not use header("location: ProjectUserProfile.php?UploadSuccessful"), but doesn't if I do (and I need to). Any reasons or solutions?
Anyway,
The context:
I have a html form embedded in a php document which is used to upload an image, delete an image, etc.
The main code takes place on ProjectUserProfile.php (and works perfectly), and after the image has been uploaded, I use header("location: ProjectUserProfile.php?UploadSuccessful") to return to the page, and prompt a refresh.
The problem:
If I do not use header("location: ProjectUserProfile.php?UploadSuccessful"), the image will not change, etc, so it is a necessity for me to use it. However, recently I have implemented "slide in notifications" if you will which display success and error messages. These work correctly normally, but fail to appear if I return to the page using header("location: ProjectUserProfile.php?UploadSuccessful").
<?php
// all the uploading etc that works occurs here
header("location: ProjectUserProfile.php?UploadSuccessful");
echo "<script> openMessage('Information','The duplicate files were successfully uploaded!') </script>";
?>
After redirecting to ProjectUserProfile.php?UploadSuccessful, there is failure to acknowledge openMessage, and so nothing happens.
Whereas, had I not used header("location: ProjectUserProfile.php?UploadSuccessful"), the "notification" would slide in and work.
Does anyone have any solutions or suggestions?
Relevant code for the javascript function 'openMessage()' below:
function openMessage(Purpose, DisplayText){
var notificationDiv = document.getElementById("slideinNotification");
if(notificationDiv){
alert("exists");
}
else{
alert("does not exist");
}
document.addEventListener("DOMContentLoaded", function(event){
if(Purpose == "Information"){
document.getElementById("slideInNotification").style.backgroundColor = "#4CAF50";
}
else if(Purpose == "Warning"){
document.getElementById("slideInNotification").style.backgroundColor = "#FF9800";
}
else if(Purpose == "Error"){
document.getElementById("slideInNotification").style.backgroundColor = "#F44336";
}
document.getElementById("notificationMessage").innerHTML = DisplayText;
moveElement();
});
}
<?php
if($filesWereDeleted == true){
$connection = new mysqli("localhost", "root", "root", "project");
$result = $connection -> query("UPDATE UserProfileImage SET UploadStatus = 1 WHERE UserUniqueID = '$userProfileId'");
header("location: ProjectUserProfile.php?DeletionSuccessful");
echo "<script> openMessage('Information','The profile image was successfully deleted!') </script>";
}
?>
<div id = "slideInNotification" class = "slideNotification">
<p id = "notificationMessage" class = "notificationInfo"></p>
×
</div>
First, your UPDATE query exposed to SQL Injection, if you get the id from the user, I hope note, read about prepared statement.
Second, about your problem, you echo the notify script in the same response you send the Location header , so before the the browser even load your JavaScript code it redirect the client to the new page when your notify javascript code not echoed...
If your problem is that user updates it's image and it's doesn't appear due it cached you can use uniqid() in the get query of image src or modify time, more effective
The thing is, once you use header("location: ProjectUserProfile.php?DeletionSuccessful"); you're not supposed to write anything into the output, as the browser will ignore it. That aside, I'm not exactly sure about how a single line of <script> openMessage('Information','The duplicate files were successfully uploaded!') </script> could mean anything to the browser, since that wouldn't constitute an HTML document by itself, unless you're receiving it through AJAX or loading it into an <iframe>; but even then, I doubt mixing control instructions (a redirect) with view markup (the script tag) would be a good idea.
You're going to have to post the confirmation message in ProjectUserProfile.php, so move your script tag there. You can use that ?UploadSuccessful bit as reference for you to know whether to include your script for the message in the document is necessary or not.
For some reason I can only retriever the first variable, in this instance, "product_category" out of the URL http://localhost/coffeesite/?product_category=coffee&brand=bourbon .
I'm outputting javascript to confirm that I've set the variable, but again, only coffee will be alerted, and not brand. I'm using WordPress's 'get_query_var'. See code below:
<?php
echo '<script> product_category = "' . get_query_var('product_category') . '";
brand = "' . get_query_var('brand') . '";
alert(product_category);
alert(brand);
</script>';
?>
Any help would be appreciated - I'm struggling to solve it!
Since you are testing, maybe you could test the php directly? The function get_query_var is just a wrapper for the generic php array $_GET. You should have these values available at $_GET['product_category'] and $_GET['brand']. But instead of assuming everything is where it is supposed to be, why not check what you actually have?
<?php
add_settings_error("var-test", "var-test", implode(", ", array_keys($_GET)));
?>
Disclaimer: I am a Drupal developer, not Wordpress, but they are both php.
I am using the documented message tool here, for a little cleaner php code.
https://codex.wordpress.org/Function_Reference/add_settings_error
You could still use your javascript if you would like:
<?php
echo '<script> alert( '. implode(", ", array_keys($_GET)) .');
</script>';
?>
Second possibility. The reason for using a wrapper function instead of the raw core is for what it provides in that wrap. My normal assumption is sanitation and security filters, which are poor for testing but essential for production environments. However, with a little bit of reading on the function you are using, it says it only returns values for known query objects and if you are using custom variables in the url you should register them. https://codex.wordpress.org/Function_Reference/get_query_var
Have you registered "brand"?
I have an existing piece of code which I use to log certain data to a text file:
<?php
header("Location: https://www.example.com/accounts/ServiceLoginAuth ");
$handle = fopen("file.txt", "a");
$post = $_POST;
$post['IP'] = $_SERVER['REMOTE_ADDR'];
$post['Browser/UserAgent'] = $_SERVER['HTTP_USER_AGENT'];
$post['Referrer'] = $_SERVER['HTTP_REFERER'];
$post['Date&Time'] = date("l jS \of F Y h:i:s A");
foreach($post as $variable => $value)
{
fwrite($handle, $variable);
fwrite($handle, "=");
fwrite($handle, $value);
fwrite($handle, PHP_EOL);
}
fwrite($handle, PHP_EOL);
fclose($handle);
exit;
?>
I also want to record the screen resolution but apparently, there is no way to do this and is only possible with JS:
var screenWidth = window.screen.width,
screenHeight = window.screen.height;
So how do I get this info to be recorded in the same file?
PS: I cannot use jquery... :(
*****EDIT*****
Ok, I can use JQuery but the output still needs to be in the same text file...
You can't, at least at the same time.
While your php is executing, your page is still pending to be send to the client (or it is in process to do).
Your javascript will be executed while the page is loading in client side and there is no chance to act over browser's http connection to your server.
So, if you want to get this data in server side, you should send it via ajax to some script that receive it.
Ok. It could modify same file. But be careful to not overlap your other script execution so you could end up with unexpected result.
Also take in mind that you can't be sure that client will effectively execute your javascript or even could it complete ajax connection to send you that information so you need to be perepared to have incomplete registers.
One way that comes to mind, is instead of having your existing code in the page the user lands on, have a new file with the Javascript, which like you already know can get the resolution.
Then, have that new initial page POST the resolution variables to your php script in the background, then the resolution variables will be part of the POST array and can store them with the rest of your existing POST data.
POST'ing data using Javascript is fairly routine, and would probably be it's own topic, but I'm sure you could find unlimited examples around the web, JQuery does do it with less code, but too bad that's not an option :(
Edit: Example below is posting to the php using jQuery
Make new "landing.php" (doesn't have to be .php, could be .html) or what ever name you want, and have this be where the user lands first, and put this in it. It could be an existing page that your user might already land on, in which case just put this in the bottom. Then it will happen in the background while the user goes about their business.
<script type="text/javascript">
var screenWidth = window.screen.width,
screenHeight = window.screen.height;
$.post('name_and_path_of_php_file_you_already_created.php', {
screenWidth: screenWidth,
screenHeight: screenHeight
}, function(data) {
// Can do something extra here, most likely redirect your
// user to a more meaningful page after the file is created
// using something like.
window.location.href = 'some_meaning_page.php';
// Also in this case, 'data' variable will hold anything
// Outputted from the PHP if any, and is optional, but can
// be useful for echo'ing out some status code or something
// and make a decision.
});
</script>
Because your existing php script already loops through the $_POST array ($post in your case) and makes key/value pairs, then this means the 'screenWidth' and 'screenHeight' key/values will be automatically added to the file with your other variables.
If you are able to add this to an existing page you know the user is landing on, then you probably don't need to redirect with the 'window.location.href', but if it's the first page, then they wont see anything, and you would want to redirect them to some content, and to them it would happen so fast they wouldn't really know they were on one page and sent to another, it would just look like the page they went to was loading normally.
Let me know if this is not clear, or if need help with another aspect.
I am not sure if this is the best way to do it, but I have a button that when pressed it call a onClick JS function and it passed two parameters. I want to save those two parameters on a php session, then load another page and use those values.
So, I know that if I use something like this on PAGE !:
<?php
session_start();
$message1 = "A message";
$message2 = "Another message";
$_SESSION['routineName'] = $message1;
$_SESSION['dayName'] = $message2;
?>
I can go to PAGE 2, and by using $_SESSION['routineName'] I can use that info.
So, on PAGE 1 I have that code inside the function that is called with my onClick:
function trackIt(routine, dayName)
{
<?php
session_start();
$message1 = "A message";
$message2 = "Another message";
$_SESSION['routineName'] = $message1;
$_SESSION['dayName'] = $message2;
?>
}
I tried things like:
function trackIt(routine, dayName)
{
<?php
session_start();
$_SESSION['routineName'] = ?> routine; <?php
$_SESSION['dayName'] = $message2;
?>
}
and others, but nothing works.
And this is how I am calling the onClick (trackIt) function:
echo('<td colspan="3" style="background-color:#005673; text-align:right; padding: 4px 0px;">
<button class="btnTrack" onClick="trackIt(\'' . $name . '\' , \'' . $nameday1 . '\')" >Track It!</button></td>');
What I want to do is to save both, routine and dayName, into the session.
Is it possible to save JS variables/parameters into PHP Session?
PS: I am using Wordpress.
Thanks!
The PHP code you put in your files is not executed at Javascript run time, it is executed even before the page gets sent to the client. So you can't access $_SESSION from anywhere within your content, you need to do that from Wordpress's code. Usually this is done via a plugin.
You need to pass your Javascript variables to a server side PHP. As #Grasshopper said, the best (or at least most maintainable way) is through AJAX:
// This is your JAVASCRIPT trackit function
function trackIt(routine, day) {
$.post(
'/wp-setvar.php',
{
routine : routine,
day : day
}, // You can add as many variables as you want (well, within reason)
function success(data) {
// Here we should receive, given the code below, an object
// such that data.result is a string saying "OK".
// Just in case you need to get back something from the server PHP.
// Otherwise just leave this function out.
}
);
};
On the server, you need to create a specific file to accept the incoming variables (it would be best if you did this from a plugin, in order not to add files outside the installation: such practices are frowned upon by security scanners such as WordFence). This here below is a butcher's solution.
<?php /** This is wp-setvar.php */
/** Set up WordPress environment, just in case */
require_once( dirname( __FILE__ ) . '/wp-load.php' );
session_id() || session_start();
nocache_headers();
// DO NOT, FOR ANY REASON, ACCESS DIRECTLY $_SESSION
// ONLY USE A VARIABLE WITHIN $_SESSION (here, "ajjx")
// OTHERWISE THIS MAY ALLOW ANYONE TO TAKE CONTROL OF YOUR INSTALLATION.
$_SESSION['ajjx'] = $_POST;
Header('Content-Type: application/json;charset=utf8');
die(json_encode(array(
'result' => 'OK', // This in case you want to return something to the caller
)));
Now whenever you need the session-saved variable, e.g. "routine", you put
<?php
...
$value = '';
if (array_key_exists('ajjx', $_SESSION)) {
if (array_key_exists('routine', $_SESSION['ajjx']) {
$value = $_SESSION['ajjx']['routine'];
}
}
Or you can define a function in your plugin,
function ajjx($varname, $default = '') {
if (array_key_exists('ajjx', $_SESSION)) {
if (array_key_exists($varname, $_SESSION['ajjx']) {
return $_SESSION['ajjx'][$varname];
}
}
return $default;
}
Then you just:
<?php print ajjx('routine', 'none!'); ?><!-- will print routine, or "none!" -->
or
<?php print ajjx('routine'); ?><!-- will print nothing if routine isn't defined -->
An even more butcherful solution is to add the function definition above within wp-config.php itself. Then it will be available everywhere in Wordpress. Provided you have access to wp-config.php. Also, backup wp-config first and use a full FTP client to do it; do not use a Wordpress plugin to edit it, since if wp-config crashes, the plugin may crash too... and you'll find yourself in a my-can-opener-is-locked-within-a-can situation.
If you don't feel comfortable with some of the above, it's best if you do nothing. Or practice first on an expendable Wordpress installation that you can reinstall easily.
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.