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();
}
?>
Related
i search internet for my question and i doesn't found how to get my $_POST on another page. Please help.
game.php:
<?php
session_start();
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
var drzewo = 0;
function save() {
$.post( "save.php", { drzewo: drzewo } );
window.location.href = "save.php"
}
presave.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<?php
session_start();
$_SESSION['drewno'] = $_POST["drzewo"];
echo $_SESSION['drewno']
?>
Undefined array key picture
Your question seems incomplete in my opinion. There are many things missing from your question. From your image I assume you are using it on local server. There are one thing that looks weird is this:
`$.post( "save.php", { drzewo: drzewo } );`
Where is this save.php file stored? Is it stored in your root file? Or along with the operating file. Put a "/" before save.php and see what happens.
There is another thing that seems awkward is your image is showing there is a presave.php file. But I found nothing about that file in your question details.
I can see that you put a redirecting code in your script. JS is not supposed to work like that. What happening here is it is doing an asynchronous operation. That is why PHP can't get the data and showing you a error. If you want to send data send it in a form. Or you can put a redirection in your PHP code after getting the post data. Since it is an AJAX call you can see some reports in your console.log() with the response data.
$.post( "save.php", { drzewo: drzewo } );
window.location.href = "save.php"
Let's analyze these 2 lines of code.
When you send a post request through javascript, it goes through an ajax request and the browser waits till the save.php completes working it's code and returns to the ajax. Here the save.php has received the $_POST data and has processed it.
This processed data by save.php will not output in the browser. It will go to the post (ajax) callback function. If you want to display the data, you need to use a callback function. See this https://www.w3schools.com/jquery/ajax_post.asp for a simple usage of $.post() function.
In the next line of your code you are redirecting your browser to save.php without sending any $_POST data. Since now your save.php does not have any information about $_POST["drzewo"] it throws an error Undefined array key "drzewo" .
Therefore instead of window.location.href page redirect, you need a callback function with your $.post() function. I hope now you understand why you are getting this error.
[Edit]- I have added some code for your better understanding. You can refer to this excellent "JQuery Ajax POST Method" tutorial from freecodecamp.org. https://www.freecodecamp.org/news/jquery-ajax-post-method/
game.php
<?php
session_start();
?>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<button id="btn" onclick="save();">Click this</button>
<script type="text/javascript">
var drzewo = 0;
function save() {
$.post("save.php", {
drzewo: drzewo
},
function(result) {
alert("This result contains the output from save.php : " + result);
//Write here the code you want to execute after the POST request is successfully completed.
}
);
}
</script>
</body>
</html>
save.php
<?php
session_start();
$_SESSION['drewno'] = $_POST["drzewo"];
echo $_SESSION['drewno'];
If you want to pass data from one URL to another, use query string. $.post() makes a POST request, but it seems like save.php is not an endpoint but actually a page.
In other words, you can do this:
window.location.href = `save.php?drzewo=${drzewo}`;
And then on save.php simply read the value from $_GET:
<?php
session_start();
$_SESSION['drewno'] = $_GET["drzewo"];
echo $_SESSION['drewno']
?>
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>
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.
Is it possible to run a JavaScript function from PHP using an Ajax call.
For example, if I have a html page in php with an ajax call. The ajax post gets sent to a php engine:
index.php
<script>
Ajax.post('http://example.com/ajaxEngine.php', { data: "someData" });
</script>
Then in the PHP engine, can I run a JavaScript function like this:
ajaxEngine.php
<?php
$data = $_POST['data'];
?>
<script type="text/javascript">
var php_var = "<?php echo data ?>";
function doSomething(php_var) {
// do something with data
}
</script>
Lastly, If the JavaScript function needs to return a value, how would you then transfer that back to php? Could I post to the same page and then get it as a variable with PHP?
Short answer: No.
Your code in ajaxEngine.php would just output that snippet of javascript. This will be transfered back to your page, so you could insert it into a script tag or eval it, if you like it to execute. But this would then happen on the client side not on your server. The script would have the dynamic data from the php, though. So if this is everything you need, it would work that way.
Beware: That would NOT hide your script. It would be visible for any client.
Try this function
function includetext(text,onlyone)
{
var d=document.createElement('script');
if(onlyone)
{
var ds=document.getElementById('onlyonesscript');
if(ds)
removeElement(ds);
d.id='onlyonesscript';
}
d.innerHTML=text;
document.body.appendChild(d);
}
text - returing text of script from ajax.
onlyone use for just one script node, this will help you.
ajaxEngine.php
<?php
$data = $_POST['data'];
?>
var php_var = "<?php echo data ?>";
// do something with data
I need to send result from my PHP file to the JavaScript function/file.
I found some of answers like: var x='<?php echo $pathinfo; ?>';
or this:
myHtmlFile.html:
<script type="text/javascript" src="jquery-1.8.1.js"></script>
<script type="text/javascript" src="newEmptyPHP.php"></script>
<script language="javascript">
function test()
{
alert(result);
}
</script>
newEmptyPHP.php:
<?php
$res="it is result";
echo "var result = ".json_encode($res).";";
?>
My question is whether there is way return value from php function and not from php file.
something like this:
<?php
function phpFunction(){
$res="it is result";
return $res;
}
?>
I need simple PHP/JavaScript code without something complex.
I want keep many function in one php file and not many php files.
<?php
function phpFunction(){
$res="it is result";
return $res;
}
?>
<script>
var result = "<?php echo phpFunction() ?>";
</script>
The above method will work. However, if you want more PHP/JS combined scripts, learn AJAX.
The best way to get your data to JavaScript from PHP is to use AJAX using jQuery you have declared.
You can use $.get()
You can call you php script which contains the function with parameters in you url request.
And when a specific parameter is specified in the url, then you can call you fonction and echo whatever you want to the javascript.
Have a good day!
You can open as many php tags as you wish inside your one php document. You can then either make this php document separate from your main document (however this would require making the main document in php and using a "php include" or "php require") or you can simply just open and close php tags as necessary. You do not even have to close the line at the end of the php, for example.
<?php if (a==a) { ?>
<div>
<script>
<?php echo 'do something here'; ?>
</script>
</div>
<?php } ?>
Using the above example can provide some unique results. Just remember that anything you do with php you can just echo out the result and slot it into the middle of your javascript.