Simple javascript PHP default variable issue - javascript

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>

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.

Javascript, PHP, and SQL Security - Basic validation of information received.

I have been developing a social network. I have noticed some security issues where the user can change the variables in javascript/jquery to other user_id's, text content, and other information that has been loaded into the scripts. And this is all done via the inspect tool or other software that can edit the languages. They can even rewrite the functions.
I load data onto the page via php and sql after sending the url_id to a php function.
I have javascript and jquery scripts that in return use this data to perform ajax, post, and get requests and to perform functions.
How can I stop the user from changing these variables before they are sent off to the server? For example when a user makes a post they can change the id to make it someone else's post, or when they click delete an image they can delete someone else's and it gets more complicated. This is a huge concern.
These scripts are included in the php pages or in php scripts that are loaded via ajax.
How can I stop this? Can you give me an easy explanation? I have been searching for months on how to stop this. I still don't understand how to stop the user from doing so. If there is another way could to do this? Can you provide me with true 100% examples? What are the other options I have?
Here are some snippets of my code
<? if (login_check($mysqli) == true) : ?>
<script>
$.post("auto/online.php?q=<? echo $id ?>");
function o() {
setTimeout(function() {
$.post("auto/online.php?q=<? echo $id ?>");
o();
}, 6e4);
}
</script>
<? endif; ?>
<?php echo '<div class="post-btn" onclick="ajaxPost(postenter.value,\''.$name.'\',\''.$id.'\');" title="Post">Post</div>'; ?>
function ajaxPost(content,name,id) {
var ip = '<?php echo $ip ?>';
content = content.replace(/<br\s*\/?>/mg,"\n");
var postArray = [content, id, ip];
postArray = JSON.stringify(postArray);
alert(postArray);
if (content.length == 0) {
alert('Oops it looks like your post is empty.');
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("postenter").innerHTML = "";
var html = xmlhttp.responseText;
alert(html);
$(html).hide().insertAfter("#wrapper").fadeIn(500);
document.getElementById("postenter").value = "";
}
}
xmlhttp.open("POST", "auto/post.php", true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send('data=' + postArray);
}
}
<? if ($id == $user) : ?>
<div class="modalSetPro" onclick="setProImage(<? echo $picID; ?>,<? echo $uid; ?>)">Set Profile</div>
<div class="modalSetBac" onclick="setProCover(<? echo $picID; ?>,<? echo $uid; ?>)">Set Background</div>
<div class="modalDelImg" onclick="delItemPre(<? echo $picID; ?>, 1, <? echo $uid; ?>)">Delete</div>
<? endif; ?>
function delItemPre(itemID, type, user) {
var modArr = [itemID, type, user];
modArr = JSON.stringify(modArr);
$("#LoadMe").load('modals/del_modal.php?p=' + modArr);
}
How can I stop the user from changing these variables before they are sent off to the server? For example when a user makes a post they can change the id to make it someone else's post, or when they click delete an image they can delete someone else's and it gets more complicated. This is a huge concern.
You can't.
Your server side code should evaluate the user's privileges and decide whether or not they can do the action. JavaScript validation is more for the user experience - guiding and preventing mistakes.
You are not able to prevent this, which is why server-side validation is required.
Here is a stackoverflow discussing it: Why do we need both client side and server side validation?
There is some good information here:
http://www.w3schools.com/php/php_form_validation.asp
Basically, you want to put your validations in the PHP page that you are posting your ajax to.
Store and check all insecure data on server side, not client. This way user can't change it.
First of all when you are working on client side you have no control how user interact with you jquery or javascript code. So thumb rule is that never expose sensitive data in html or java script.
More over If you are curious about security you have not required to load User id in hidden field or any other client side code(html). In you case like when user is replying to any post you have to crosscheck at server side whether current logged in user is authorized to perform this task or not. also cross check whether this post is relate to current logged in user.
I have no knowledge about php but in asp.net we can create a session at server side and when user post data get the User id from session not from html content posted by user.

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>

PHP: Not changing the value of a variable

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

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