Javascript is loading rest of the script also - javascript

i am using to confirm deletion of a content.
i have used js to confirm user to delete the content.. but if user cancels the confirm dialogue, it should redirect.. but instead the page is loading the whole script and then redirecting!
the script goes here...
if (confirm("Are you sure you want to delete??"))
alert("deletion successful");
else
history.go(-1);
alert("unwanted alert");
this unwanted alert is also displayed when i am clicking on cancel in confirm dialogue box..
Edit..
actually the whole code goes like this.. maybe this will give a clear view of what my problem is
<html>
<script>
if (!confirm("Are you sure you want to delete??"))
history.go(-1);
</script>
<?php
require_once "config.php";
$query= 'DELETE FROM `sess` WHERE `sid` ='.$_GET['bid'];
if ($conn->query($query) === TRUE) {?>
<script>
alert("deletion successful");
window.location.replace("../index.php");
</script>
<?php
} else {?>
<script>
alert("unable to delete!");
window.location.replace("../index.php");
</script>
<?php }?>
</html>

Your edit reveals the problem.
Your PHP code runs on the server and before the page is delivered to the browser. So even though you output JavaScript code asking the user whether they want to confirm, that doesn't do anything until the page is sent to the browser. Your server-side code continues to run, executing the SQL statement.
So basically, breaking it into server and client parts, here's how your code runs:
First, this server-side code runs:
require_once "config.php";
$query= 'DELETE FROM `sess` WHERE `sid` ='.$_GET['bid'];
if ($conn->query($query) === TRUE) {
/*...write some output to the response...*/
} else {
/*...write some other output to the response...*/
}
Then, when the response is sent to the client, it looks like this (assuming the query call returned TRUE):
<html>
<script>
if (!confirm("Are you sure you want to delete??"))
history.go(-1);
</script>
<script>
alert("deletion successful");
window.location.replace("../index.php");
</script>
</html>
At this point, the deletion has already happened. The browser receives this response and shows the confirm and the alert and does the update to the location, but again, that has no effect on what happened on the server earlier.
You'll need to have the confirmation happen earlier, on whatever page is calling this page, so it happens before the server-side code is run.
I recommend stepping back from your current task and working through some good PHP and web tutorials, so you can better understand where and when things happen.

Related

External php file that is loaded into index.php with .load() method not recognising $_SESSION variables

So my main page loads other php pages into it with click of a button so it can be a single page website without having to load all the content at once.
index.php
<?php
session_start();
?>
<head>
$('#btnPetShop').one( "click", function(){
$( "#page_shop" ).load( "shop.php" );
});
</head>
<body>
<?php
echo session_status();/----Always returns 1, no matter if logged in or not----/
if(isset($_SESSION['admin']))
{
if($_SESSION['admin']==1)
{
/----this part works, I am logged in as admin----/
}
}
?>
<div id="page_shop"></div>
</body>
shop.php
<?php
if(isset($_SESSION['admin']))
{
if($_SESSION['admin']==1)
{
}
else{}
}
else{} <----I end up here as if $_SESSION['admin'] is not set----/
/----code entered here loads fine----/
?>
The idea is to make a delete and edit button (if you are logged in as admin) on every article in shop.php.
Problem is that $_SESSION['admin'] is recognized on index.php, but not inside shop.php
I tried typing the content of shop.php directly into and it works, the problem is that i want it to load with a click of a button.
Where ever ( in any PHP page) if you want to use any Session variable then you have to first declare session_start(); so, in your case if you have $_SESSION['admin']="User1234" on index.php and if you want to use value of $_SESSION['admin'] in shop.php then you have to again declare session_satart(); and then use it. For example, If let consider that index.php has session variable $_SESSION['admin']="User1234" and now you want to print "Welcome User1234" on shop.php then you can do it as shown below.
index.php
<?php
session_start();
$_SESSION['admin'] = "User1234";
?>
Shop.php
<?php
session_start();
echo "Welcome, ". $_SESSION['admin']
?>
Output:
Welcome, User1234
You need to add session_start(); in each page that needs access to the session data.
See: http://php.net/manual/en/function.session-start.php
EDIT
Since the solution mentioned in my original answer does not work for you and session_status() returns 1 in your code, it means sessions are enabled on your server. There is only one thing left which could explain that your sessions are lost:
You are loading shop.php with an AJAX request, is the URL exactly in the same domain as index.php? Try to add the full path before shop.php to see if this solves the issue.
Just to be clear, if your index.php runs on http://localhost/test/index.php, your new code will be:
$( "#page_shop" ).load( "http://localhost/test/shop.php" );
Well okay, I feel dumb... I found the solution.
I had this as a script
$('#btn_logout').click(function(){
<?php session_destroy();?>
});
This is a big no no and if you do this you should be ashamed

Running a php script asynchronously

I have a web page with a button, when a user taps the button there is a long php script that runs (say to look at past tokens bought by the user) and sends the user an email at the end of script.
I have abstracted my code for sharing purpose (replacing the script with just a sleep function).
webpage.php
<div class="card">
<input type="submit" class="button" name="update" value="Update" />
</div>
<script type = "text/javascript" src="jquery_functions.js"></script>
jquery_functions.js
$(document).ready(function(){
$('input[name="update"]').click(function() {
$.post(
"script.php",
{update:"fav_tokens"},
function($data) {
alert ($data.message);
},
"json"
);
});
});
script.php
<?php
sleep(60);
?>
The problem is that as soon as the user presses on the button, he is "locked in" on the page and cannot navigate away from it... which kind of defeats the purpose of doing the jQuery AJAX thing.
I have tried putting the script in another file (script2.php) and then call it using exec("php -f script2.php"); in script.php but that also stop the user from navigating away from the page.
What can I do to make this work?
The likely issue is that script.php is opening a session and whichever page you are trying to visit is also trying to open a session but has to wait until script.php is all set with it.
Somewhere in script.php you will need to add:
ignore_user_abort(1); // Let the script run even if user leaves the page
set_time_limit(0); // Let script run forever
session_write_close(); // Close the session. This will allow for other pages to open it
// You will still be able to read your session data but can no longer write to it unless it is re-opened
sleep(60);

PHP mail function gets triggered every time i load the page

I am trying to send mails using PHP's mail() function.
I have a button (Send Mail), clicking on which the mail has to be triggered. Since PHP is a server side scripting language, I used Javascript to trigger the PHP function. A very unusual event occurs. Whenever I load the page, the mail gets triggered. So, I put alerts and echos to check if the code logic is correct.
Funny thing is that the mail does not get triggered when I click the button. Where am I going wrong?
Please see my code:
<input type="button" onclick="jMail()" value="Send Mail"/>
<script>
function jMail()
{
alert("Inside Javascript Function");
alert("<?php PHPFunction(); ?>");
}
</script>
<?php
function PHPFunction(){
echo("Inside PHP Function");
mail("to#example.com", "Help Mee", "Definitely Help me", "From:from#example.com");
echo("Mail Sent");
}
?>
PHP is a server side language, while Javascript is a client side language. I think you are confusing the two, and trying to mix their use in a way that would never work.
When the page is loaded, these steps occur in sequence:
The server interprets the PHP code in your page, and renders a page that does not contain any PHP code.
The client, viewing the page, does not obviously have access to any PHP function, because it sees only the result of the elaboration. It still can use Javascript to achieve dinamic behavior of the page (i.e. changes without refreshing), and things like AJAX to make requests to the server still without re-rendering the page.
<input type="button" onclick="jMail()" value="Send Mail"/>
The event onclick is indeed triggered when you press the button, but after the page has been fully loaded. At this time, all the PHP code has been already interpreted by the server, and there is no chance to execute it again without reloading the page.
EXAMPLE: here you can see the result of the elaboration of your code (under stdout). As you can see, the client is left with a PHP-free web page.
If you're looking for a way to trigger PHP code when an event occurs after the page has been loaded, I suggest you take a look at this question.
Also, this question on programmers.stackexcange.com could help you clarify the difference between client side and server side if it isn't clear.
You cannot trigger PHP from javascript that way. Create another PHP file, and call it using AJAX javascript requests.
<form method="post">
<input type="submit" value="Send Mail" />
</form>
<?php
if(isset($_POST)){
///do sent mail here
mail("to#example.com","Help Mee","Definitely Help me","From:from#example.com");
}
?>
PHP is a server side scripting language which has already been interpreted by the server and then sent to client(i.e browser) for interpretation of any client side script( ex JavaScript).
But if want a responsive webpage to be handled by your server try to use Form and inputs tags and their attributes to send your request back to server
But if you want a Quick way Try using AJAX.
every time you do
<?php PHPFunction();
you send the mail..
maybe you could play with something like
<?php
if(array_key_exists('postMail',$_POST)){
echo ("Inside PHP Function");
//if(empty($_POST['mailContent'])){/*angry blablabla*/}
mail("to#example.com","Help Mee",$_POST['mailContent'],"From:from#example.com");
echo ("Mail Sent");
die();
}?>
<input type="button" onclick="jMail()" value="Send Mail"/>
<script>
function jMail()
{
alert("Inside Javascript Function");
var xhr=new XMLHttpRequest();
xhr.open("POST","?");
var fd=new FormData();
fd.append("postMail","true");
fd.append("mailContent","fooooobar");
xhr.send(fd);
}
</script>

How would I call a java script function using php if statement with $_SESSION

Hi I am creating a website with a login section this is working I am using HTML and PHP. What I am trying to do is one of my pages has a html button I want this to be disabled for certain users. at the moment this is what I have got.
this is the part that I use for the login details.
<?php
session_start();
$_SESSION["username"];
$_SESSION["password"];
$_SESSION["access"];
?>
I have got if statments that I am currently using which are
if($_SESSION["access"] == "Administrator"){
echo $Admin;
}
what I am trying to do is call a javascript function within a PHP if statement what i have got so far is
<?php
if($_SESSION["access"] == "Consumer")
{
echo '<script type="text/javascript">
Disable();
</script>';
}
if($_SESSION["access"] == "Administrator")
{
echo '<script type="text/javascript">
Enable();
</script>';
}
?>
the javascript functions that i am trying to call are
<script type="text/javascript">
function Enable() {
SubmitButton.disabled = false;
}
function Disable() {
SubmitButton.disabled = true;
}
</script>
I have also tryed
if($_SESSION["access"] == "Consumer")
{
echo "<script> Disable(); </script>";
}
Im just wondering if I have typed something in wrong or if I have forgotten to put something in.
any help would be much appreciated.
Looking at your code you have couple of issues:
Mixing your PHP logic and pure HTML is (usually) not a good idea.
Instead I would suggest you move your access checking logic fully on the server side and display the button accordingly (disabled or enabled) based on the user's access.
Example:
<?php if($_SESSION['access']): // Only show the button for users with access ?>
<button type="submit" value="Submit" <?php echo ($_SESSION['access'] != 'Administrator' ? 'disabled' : ''); // Button disabled for everyone but administrators ?> />
<?php endif; ?>
And let me point out the obvious (as mentioned by the other answers), that's not 100% bulletproof. The user can still manually submit the button even if he is not an administrator by editing the page's HTML on the fly. That's just a UI fix. The real check should be done on the server side once the button is submitted (e.g. is the user logged in, does he have a cookie on his computer that identifies him as an administrator, does he have a session cookie set, etc).
Calling JS in random places, e.g. in the header can have unexpected consequences.
You better wait for the page to be loaded fully before calling any JS functions. You can do that via jQuery easily, but make sure you include the jQuery library before that in your header like so.
Afterwards you can call any JS after the page is loaded by placing them within the following block:
$(function(){
// Place your JS calls here, e.g. call to Enable()
});
String concatenation in PHP is done with a dot . and strings can be multiline
This code which you used is just plain wrong.
echo '<script type="text/javascript">'
, 'Enable();'
, '</script>';
You should use something like:
echo '<script type="text/javascript">'
.'Enable();'
. '</script>';
or better:
echo '<script type="text/javascript">
Enable();
</script>';
PHP doesn't use , sign for joining. Use ..
But otherwise it should work, except that you should define SubmitButton in advance of using it.
<?php
echo "<script type='text/javascript'>";
// if the id of your element is "submitButton"
echo "var submitButton = document.getElementById('submitButton');";
echo " function disable(){ submitButton.disabled=true; }";
echo "</script>";
?>
After that you can use it as you did..
<script type='text/javascript'>
disable();
</script>
Just be advised that denying access to some elements/functionality on your webpage with JavaScript alone is not a good practice - JavaScript is executed locally on the user's computer and therefore the user can modify it to gain an advantage.
Well, the problem may be that you're trying to call the javascript function before the HTML is ready (or finally rendered), so the browser, when executes the function doesn't find the button.
You could solve this placing your javascript code at the end of your page, or using jQuery and doing:
$(document).ready(function() {
<%php if ($_SESSION['access'] == 'xxxxx') {%>
Enable();
<%php } else { %>
Disable();
<%php } %>
});
Anyway, ALWAYS check user permissions on the server side, because someone could enable the button using Firebug or something else...

Firefox pop-up PHP session variable not being sent correctly

Everything is working fine in Chrome, but not in FF. Here's my situation:
Parent page has a link, on click it creates a pop-up with a text field.
That information is stored in $_SESSION and is used to navigate (ie, "one" takes you to page one, "two" takes you to page two, etc.). In the pop-up, on submit three things happen:
The textfield info is stored in session.
The Parent page refreshes using text field data to tell it where to go.
The pop-up closes.
Keep in mind, this is working fine in Chrome. However, in FF I believe it is closing the pop-up window before the info is sent to parent window, thus losing $_SESSION data. I believe this because if I make it so the pop-up doesn't close, it works fine, so it's not a case of the pop-up not sending the data back to parent window.
SO...
I think my problem is in the order that my JavaScript is being executed, even though my ordering appears correct. And again, it functions in Chrome just fine.
Here's my code, can you solve it?
(All pages have $_SESSION in header, etc, it's not a syntax problem)
I believe Firefox is closing the pop-up before the $_SESSION data is being sent! I don't know why! What happens is my browser ends up in navredirect.php, with no an empty session. It's not getting the $_SESSION data, so the PHP if statement doesn't tell it do the meta redirect. PRINT_R yields nothing.
Parent page pop up call:
Go to Page
Code for pop up page. (enternav.php)
<head>
<script type="text/javascript">
function proceed(){
opener.location.reload(true);
window.opener.location.href='http://www.page.com/navredirect.php';
self.close();
}
</script>
</head>
<body>
<form method="post" onsubmit="proceed()" action="logscript.php">
<input type = "text" name="page" />
<input type ="submit" value="Go to page" />
</form>
</body>
Code for logscript.php (turns text-field into session data)
<? $_SESSION['pw'] = $_POST['page']; ?>
Code for navredirect.php (
<?
if($_SESSION['pw'] == "one") {
echo "<meta http-equiv=\"refresh\" content=\"0;URL=pwone.php\">";
}
elseif($_SESSION['pw'] == "two") {
echo "<meta http-equiv=\"refresh\" content=\"0;URL=pwtwo.php\">";
}
else {
echo "<meta http-equiv=\"refresh\" content=\"0;URL=wrongpw.php\">";
}
?>

Categories

Resources