PHP: Not changing the value of a variable - javascript

I have a problem in confirmation message when the USER click CANCEL the value of $IsCanceled = "yes"
then when I click OK the value of `$IsCanceled = "no"..
The problem is, when I click the OK the value of $IsCanceled is still yes...
<?php
else { ?>
<script>
var myVar = "<?php echo $bldg[$i]; ?> station is already full. Do you want to save the other networks?";
if (confirm(myVar)) {
<?php $IsCanceled = "no";?>
} else {
<?php
$IsCanceled = "yes";
?>
}
</script>
<?php
}
//and so on...
I already traced everthing but its still "yes" the value..
Thanks

PHP and Javascript.
Two completely different languages used in various different tasks.
What you have written above tries to mix two languages, which if you were writing in any other environment you wouldn't even consider doing. The above script you have written, will run its PHP when on the server, and produce an output that is sent to the browser.
In your case, that will look something like:
<script>
var myVar = "i station is already full. Do you want to save the other networks?";
if (confirm(myVar)) {
} else {
}
</script>
That is the exact output of your code at the moment. If you want to navigate the user to "save to other networks", you would have to create a hidden HTML form, with an <input type="hidden" .. that can hold the answer you need. Then, with Javascript, you can show your confirmation dialog and populate the HTML form, submit it, and handle it again with PHP.
Think of it like Tennis. You cannot change the way you hit the ball, after already sending it to the opponent. In this case, you can program both sides and make them handle the tennis ball accordingly.

php is server side scripting it can not assigned without page refresh.
Use javascript(client side scripting) variable to assign yes or no
else
{
?>
<script>
var myVar = "<?php echo $bldg[$i]; ?> station is already full. Do you want to save the other networks?";
if (confirm(myVar)) {
IsCanceled = "no";
} else {
IsCanceled = "yes";
}
alert(IsCanceled);
</script>
<?php
}

If you want to do some logic at client side you need to use JS without PHP in it.
And if you need to do logic server side so you need to POST or GET to the server.
Just open your page as source right after it loaded and you will see, that in place where you put PHP condition will be nothing.
It's because PHP already done all it's work. Check $IsCanceled and show page to you.
ALSO note, that if you need to check instead of assign you need to use double equals sign instead one e.g. if($IsCanceled == 'no') will check if variable IsCanceled equals string 'no'. BUT if($IsCanceled = 'no') tells php to assign string 'no' to variable IsCanceled it will be TRUE always because it's assignment and result of assignment is TRUE

Related

JavaScript function won't run after using header(), but does run if no use of header() (in php)

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.

Simple javascript PHP default variable issue

I don't know why I can't figure out a way to do this... This is basic programming logic. For some reason, my mind is just not working right today though. I have a page that loads and runs some javascript. When the page firsdt loads, the javascript needs to run using a default variable, however when a user clicks a link on the page, a PHP variable is set which gets sent to the javascript side of things changing the outcome of the javascript if statement. For some reason though, I just cant figure out how to get this to work. Please help.
<?php
$username = $_POST['username'];
?>
<script type="text/javascript">
// Change the username
var phpusername = "<?php echo $username; ?>";
if(phpusername == (undefined || null)) {
(This is where the default condition code will go)
} else {
(This is where code will run when user updates username)
}
</script>
There is a little more to this story as to why I am doing things this way (Using both PHP and Javascript), so please resist offering radically different solutions. There is a LOT more to this puzzle not shown here, however the rest of the puzzle does not necessarily effect the functionality of this part.
Thanks!
<?php
$username = isset($_POST['username'])?$_POST['username']:''; // set fallback value
?>
<script type="text/javascript">
// Change the username
var phpusername = '<?php echo $username; ?>';
if(phpusername == '') { // check if empty
(This is where the default condition code will go)
} else {
(This is where code will run when user updates username)
}
</script>

PHP session data removed by java refresh

Thank in advanced,
I was looking at creating a linked dropdown menu and found tutorial/code online
I have used this code twice to create lmsdropdown.php and clubdropdown.php. I am able to store the values from the lmsdropdown form is a session and echo them to clubdropdown (just for verification that values are present).
lmsdropdown is a php include within members.php and clubdropdown is an include in members2.php.
When I select a value on clubdropdown the page refreshes to populate the 2nd dropdown box and this results in my session data being cleared.
I am new to PHP/Javascript so the answer may be very obvious but this has had me stumped for a few days now. Any help would be very much appreciated.
Below is a merge of two snippets members2.php, that has taken the output of lmsdropdown and stored output in sessions.
clubdropdown shows the java code and also the echo session statements
I am able to correctly echo the session data however the javascript seems to remove this when building dropdown 2.
members.php session data
<?php
session_start();
$_SESSION['lms'] = $_POST['lms'];
$_SESSION['week'] = $_POST['week'];
if (!isset($_SESSION['usr_lvl']) or ($_SESSION['usr_lvl'] != 0)) {
header("Location: login.php");
exit();
}
?>
clubdropdown output of session data
<SCRIPT language=JavaScript>
function reload(form) {
var val = form.lge.options[form.lge.options.selectedIndex].value;
self.location = 'members-page2.php?lge=' + val;
}
</script>
</head>
<body>
<?php
$usr = $_SESSION['usr_id'];
#$lge=$_GET['lge']; // Use this line or below line if register_global is off
if(strlen($lge) > 0 and !is_numeric($lge)){ // to check if $lge is numeric data or not.
echo "Data Error";
exit;
}
$usr = $_SESSION['usr_id'];
$lms=$_SESSION['lms'];
$week=$_SESSION['week'];
echo "<br>Value of \$week = $week<br>Value of \$lms = $lms <br>Value of \$usr = $usr";
The image below shows the session variables outputted to clubdropdown that is included in members2.php
clubdropdown with variables shown
This image shows the errors after a selection is made from th 1st dropdown.
Error after list refresh
From some of the answers to similar questions on here I assume the error is because the post data is being overwritten/removed on refresh but I thought that's what the session was for?
Any input is greatly received thank you.
You are getting the values from $_POST, which the second time you run the page is absent. You need to add an If(isset($_POST['lms'])){ $_SESSION['lms'] = $_POST['lms']; } so that it is skipped if the $_POST value isn't present.
Currently, your $_SESSION variables are still there, but are being replaced with empty $_POST values.
I suspect you might be better off using an AJAX call to populate your dropdown list.

JS and PHP variable don't show good

If this was in asks, sorry for that, but I want to speed help, thanks!
Do you have suggestions for result this ? Because when I do this it show last $name, it doesn't work.
JavaScript:
var name = 'Test';
if(name === 'Test'){
<?php $name = "Test"; ?>
} else {
<?php $name = "Error"; ?>
}
I have click function and when I click I check ID of object, but after this I want check this id is good e.g. (if(id === 'content')) and show good alert, when i checked it.
This is your server-side code, which will execute exactly once when the page is requested:
$name = "Test";
$name = "Error";
After this code executes, $name will be "Error". Every time.
This is your client-side code, which will execute exactly once when the page renders in the browser:
var name = 'Test';
if(name === 'Test'){
} else {
}
After this code executes, name will be 'Test'. Every time.
You're trying to mix server-side code and client-side code. They don't mix like that. They execute on two completely different platforms at two completely different times in two completely different contexts. Whatever you're trying to do (which we don't know), this isn't how you do it.
The way you wrote it isn't going to work. First of all PHP is executed before the JavaScript is parsed. In your code you set a variable inside PHP, so nothing actually happens. If you want something written on the page use echo or print.
What I think you want is to send a variable to PHP. For this you need a form or an Ajax-call.
If you want it the other way around, set a JavaScript variable based upon a PHP value you need to use JSON notification.
The only way I could even think of doing this would be:
<script>
var name = 'Test';
if(name === 'Test'){
</script>
<?php $name = "Test"; ?>
<script>
} else {
</script>
<?php $name = "Error"; ?>
<script>
}
</script>

How to make a menu that will change the language of my site

I am new to web development and I want my site to have a drop-down menu that will change the language of my site.I want a solution that will not require me to create a whole new html of the new site. I also want a way to make an input field that will ask users to add a number and then it will automatically add a word after the number.
Perhaps this maybe of some use to you - http://code.google.com/p/jquery-translate/.
Not sure what the second part of the sentence is but a somewhat easy way of doing this is server-side scripting. For example, if you are using PHP, I would recommend you echo the a variable instead of actually typing the contents in the place it belongs. Instead, store the content in a database and then load the content from a database depending on what language is selected (store this a session variable), store it in the variable and when the variable is echoed, bam.
Create in PHP by using $_GET[l];
<?php
if($_GET[l]=='en')
{
echo 'Welcome';
}
else if($_GET[l]=='sk')
{
echo 'Vítajte';
}
else if($_GET[l]=='de')
{
echo 'Wilkommen';
}
else
{
echo ''; //Here set your default language. For example if is not set- automatically to english
}
?>
Menu:
<?php
if(isset($_GET[topic]))
{
//This is code, if you use another $_GET[...]
//Without this, page will crash ,while it shows another thing
echo 'English';
echo 'Slovensky';
echo 'Deutsch';
//?l=lang changes to &l=lang
}
else
{
//Link with normal ?l=lang, cause page does not use another $_GET[...]
echo 'English';
echo 'Slovensky';
echo 'Deutsch';
}
?>

Categories