javascript condition not working with sql - javascript

If condition will work in else case also
<script type="text/javascript">
var r=confirm("Do you want to Delete ?");
//alert(r);if (r==true){ alert("You pressed OK!"); document.write("<?php $conn = Yii::app()->db; ?>"); document.write("<?php $sql1 = "DELETE FROM `table_name` WHERE c_id=$c_id"; ?>");
document.write("<?php echo $sql1; ?>"); document.write("<?php $command=$conn->createCommand($sql1); ?>"); document.write("<?php $command->execute(); ?>");
}else { alert("You pressed Cancel!");history.go(-1); }
</script>

PHP is a server-side language. You are generating PHP code from client-side JavaScript. The browser will just render it as (invalid) HTML.

Check your PHP commands:
$command=$conn->createCommand($sql1); // This return "echo" command?
$command->execute(); // And this?
Try this:
document.write("<?=$sql1?>");
document.write("<?=($command=$conn->createCommand($sql1) ? 'SQL created with success!' : 'SQL fail')?>");
document.write("<?=($command->execute()?'SQL executed with success!' : 'SQL command fail')?>");

PHP is meant for server side functions. javascript allows a page on client side to interact with the server in an easier way. The better way to accomplish what you are trying to do, would be to post to the php via javascript and let the php function handle the data and transactions.
This is very bad code practice. I will not go to particulars but really bad.
Here's more or less what it should/could look like ::
JQuery(much easier than javascript) ::
$(document).on('click',$('#someUniqueButtonID'),function(){
var r = confirm('are you sure?');
if(r){
$.post(<?php echo #URL_for_controller/function ?>,#DATA_TO_SEND,function(status){
alert('your Query was' + status);
//What you want to do after
});
}
})
PHP ::
function Delete($id) {
$sql1 = "DELETE FROM `table_name` WHERE c_id=$id";
$command = Yii::app()->db->createCommand($sql1)->execute();
echo "Successful";
}
Not a perfect example but it will help with code readibility and much better code practice. as #user574632 mentioned. php and javascript dont work well like that. Many times we use php to get the url of an action, but the "work" should be done by php in a controller action.

Related

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>

How to restrict $_SESSION[] using Javascript?

I wanna get just $_SESSION["yetki"] value when I call users function actually I am getting value but always getting "manager" value even if user equal student .
<script>
function users(tik) {
var user = tik.id;
if(user === "student")
{
<?php $_SESSION["yetki"]="student"; echo $_SESSION["yetki"]; ?>
}
else ()
{
<?php $_SESSION["yetki"]="manager"; echo $_SESSION["yetki"]; ?>
}
}
</script>
What you are doing is completly wrong, you are mixing both client side and server side code, javascript is client side code and php is server side language. In your if else condition you need to send request to server to set that session variable. For sending request to server you can use ajax.
Actually, you got all your fundamental understanding of Php and JavaScript wrong. By the time that this script is already running in the client's web browser, the Php scripts would have been processed/executed already and echoed into the document body.
Here's how it works. When you ask for a Php "page", the server would execute every Php script in that page and generate a response. That response would be the one that your web browser would execute.
for example, if you do this:
<script>
if (<?Php echo "true"; ?>) { alert ( 'The server said true' ); }
else { alert ( 'The server didn't say anything' ); }
</script>
The one you'll see in your web browser is:
<script>
if (true) { alert ( 'The server said true' ); }
else { alert ( 'The server didn't say anything' ); }
</script>
What Php does is to create dynamic contents for the webpage and send it back to the client. The client's web browser would then execute the result of that generated content. The Php codes would all be executed as soon as you requested for the web page - the process all happens in the server. JavaScript, on the other hand, would execute AFTER the client receives the web page.
In fact, "echo" is a pretty descriptive term of what Php does. When you type a web address in your browser's address bar and press enter, you are sending a request to the server. Once it "hits" the server, it will "echo" a response in the form of HTML. That HTML would then be read by your web browser and that would include everything from Javascript to CSS. And yes, you can even echo a whole mix of HTML elements and Javascript content. You can even echo the whole document body.
for example:
<?Php
echo
<<<YOURCONTENT
<HTML>
<HEAD></HEAD>
<BODY>You're gonna love my body.</BODY>
</HTML>
YOURCONTENT;
?>
WHAT YOU SHOULD DO FIRST is to validate what the contents of $_SESSION["yetki"] would be.
<?Php
if(your conditions here)
$_SESSION["yetki"]="student";
else
$_SESSION["yetki"]="manager";
?>
<script>
function users(tik) {
var user = tik.id;
if(user === "student")
{
alert('<?php echo $_SESSION["yetki"]; ?>');
}
else
{ // I DON'T KNOW WHAT YOU'RE TRYING HERE, BUT LET'S DO AN ALERT.
alert('<?php echo $_SESSION["yetki"]; ?>');
}
}
</script>
possible conditions for Php if statement:
$_POST['yourFormInputName'] == 'yourRogueValue'
or
$_GET['yourURLVariableName'] == 'yourRogueValue'
or
$_SESSION['perhapsAnotherStoredSession'] == 'yourRogueValue'
you can do with something like this.. but don't know is this a good answer
<script>
function users(tik) {
var user = tik.id;
if(user === "student")
{
var aa = "<?php $_SESSION["yetki"]="student"; echo $_SESSION["yetki"]; ?>"
}
else
{
var aa = "<?php $_SESSION["yetki"]="manager"; echo $_SESSION["yetki"]; ?>"
}
alert(aa);
}
</script>

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 I Can move variable from JavaScript into a php Query?

Here is my Code I want to move my Variable of "Hellow"
from JavaScript
to PHP Query at:
document.write("<?php $result = mysql_query("SELECT Urdu FROM translate where English= 'Variable'"); ?>");.
Kindly any help?
<script type='text/javascript'>
var Variable = "Hellow";
document.write("<?php
$db = mysql_connect("localhost","root","");
mysql_select_db("Dictionary",$db);
?>");
document.write("<?php $result = mysql_query("SELECT Urdu FROM translate where English= 'Variable'"); ?>");
document.write("<?php
while($row = mysql_fetch_array($result))
{
echo $row['Urdu'] ;
}
mysql_close($db);
?>");
</script>
You can't/should not do what you propose. JS is executed client side, while PHP is a server side language, and even if it is possible to send a file to the server and execute it, it would come with a host of security issues.
What you could do however is to make a get/ajax request that sends your variable to a php script, but remember to clean up the variable before using it in any mysql query.
What you are trying to do won't work because the PHP processing happens earlier in the stack than the Javascript. You will need to use ajax to send data back to the server once the page has loaded.
jQuery can make this pretty easy for you. Look up $.ajax methods for jquery.

Calling php function after javascript confirmation

I want to call function deleteUser() after JavaScript confirmation. Here is my code. Please help me.
<?php
session_start();
include_once("DataSourceController.php");
$DeletedBy = $_SESSION['ID'];
$Name = $_GET['uname'];
echo '
<script type="text/javascript">
var responce=confirm("Are you sure you want to delete this user?");
if (!(responce==true)){
deleteUser();
}
</script>';
function deleteUser(){
$sql_DeleteUser="UPDATE login
SET Deleted=1,DeletedAt= now(),DeletedBy=".$DeletedBy."
Where User='".$Name."';";
mysql_query($sql_DeleteUser);
echo'
<script type="text/javascript">
alert("User '.$Name.' Successfully deleted.");
window.location.href = "../pages/DeleteUser.php";
</script>';
}
?>
You have a few mistaken theories in your initial question. Although JavaScript is a client-side language, PHP is not. You will get an undefined function error with your current code, since it is not defined in javascript.
In order for JavaScript to execute a PHP function, it would be highly recommended to learn and use AJAX. AJAX can be used to dynamically execute PHP code when a user does a certain action. Many websites use this to query the database without reloading a page.
JavaScript will send a request to a PHP page, where the function will be executed. Refer to this page for a more in-depth example: Call PHP function from javascript
You can do it by to ways :
1/ Synchronously by redirecting to a php script by sending informations thanks to GET (for example):
<script type="text/javascript">
var responce=confirm("Are you sure you want to delete this user?");
if (!(responce==true)){
window.location.href = ("myScript.php?user="+userName); //var userName should be defined before
}
</script>';
and myScript.php:
<?php
if isset($_GET['user']){
$name = $_GET['user'];
}
//some stuff
deleteUser($name); //Here you call your function
header('Location: myPage.php'); //You return to your first script
?>
2/ Asynchronously by calling an AJAX request to myScript.php
Use this code:
<?php
session_start();
include_once("DataSourceController.php");
$DeletedBy = $_SESSION['ID'];
$Name = $_GET['uname'];
function deleteUser(){
$sql_DeleteUser="UPDATE login
SET Deleted=1,DeletedAt= now(),DeletedBy=".$DeletedBy."
Where User='".$Name."';";
mysql_query($sql_DeleteUser);
echo'
<script type="text/javascript">
alert("User '.$Name.' Successfully deleted.");
window.location.href = "../pages/DeleteUser.php";
</script>';
}
//first, we check whether the user has confirmed or not
if(!isset($_GET['confirmed'])) { //if they haven't, we display the confirmation message
?>
<script type="text/javascript">
var responce=confirm("Are you sure you want to delete this user?");
if (!(responce==true)){
//if confirmed, reload the page with added 'confirmed' parameter
window.location.href="<?php echo $_SERVER['PHP_SELF'].$_SERVER['REQUEST_URI'] ?>?confirmed=1"
}
</script>
<?php
}
elseif($_GET['confirmed'] == 1) {
deleteUser();
}
?>

Categories