最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Call php function with onclick event? - Stack Overflow

programmeradmin0浏览0评论

I want to delete project from database.Before deleting I want to confirm it whether user want to delete or not.If user click on okay it has to call delete function.But in the code when user click the function is get called not only user click on okay but also click on concel.For other alter statement it is working fine.For calling php function only it gives problem.

How can I solve this?

code is,

<a href="http://localhost/Performance/project/ShowAllProjects.php?project_id='.$row['project_id'].'"><img src="http://localhost/performance/css/delete.png" title="delete"  alt="running test" style="width:15px;height:15px;border:0;margin-left:1cm" Onclick="deleteProject();"/></a>

<script>
    function deleteProject() {      
        var r = confirm("Press a button!");
        if (r == true) {
            //alert("You pressed OK!");
            alert("<?php confirmDelete(); ?>"); 
        } else {
            alert("You pressed Cancel!");              
        }
    }
</script>

<?php
    function confirmDelete(){
        $sql="DELETE FROM project_table WHERE project_id='".$_GET['project_id']."' AND member_id='".$_SESSION['user_id']."';";
        if(mysqli_query($GLOBALS['db'], $sql)) {
            echo "Your test deleted successfully";  
        } else {
            echo "ERROR: Could not able to execute $sql. " . mysqli_error($GLOBALS['db']);
        }
    }
?>

I want to delete project from database.Before deleting I want to confirm it whether user want to delete or not.If user click on okay it has to call delete function.But in the code when user click the function is get called not only user click on okay but also click on concel.For other alter statement it is working fine.For calling php function only it gives problem.

How can I solve this?

code is,

<a href="http://localhost/Performance/project/ShowAllProjects.php?project_id='.$row['project_id'].'"><img src="http://localhost/performance/css/delete.png" title="delete"  alt="running test" style="width:15px;height:15px;border:0;margin-left:1cm" Onclick="deleteProject();"/></a>

<script>
    function deleteProject() {      
        var r = confirm("Press a button!");
        if (r == true) {
            //alert("You pressed OK!");
            alert("<?php confirmDelete(); ?>"); 
        } else {
            alert("You pressed Cancel!");              
        }
    }
</script>

<?php
    function confirmDelete(){
        $sql="DELETE FROM project_table WHERE project_id='".$_GET['project_id']."' AND member_id='".$_SESSION['user_id']."';";
        if(mysqli_query($GLOBALS['db'], $sql)) {
            echo "Your test deleted successfully";  
        } else {
            echo "ERROR: Could not able to execute $sql. " . mysqli_error($GLOBALS['db']);
        }
    }
?>
Share Improve this question edited Jun 5, 2018 at 8:37 coudy.one 1,43013 silver badges24 bronze badges asked Jun 5, 2018 at 7:20 VidyaVidya 4021 gold badge8 silver badges17 bronze badges 7
  • 1 alert() is used for display message, not for calling a function. – Devsi Odedra Commented Jun 5, 2018 at 7:22
  • you can try with console.log() instead of alert() – Nawin Commented Jun 5, 2018 at 7:24
  • you should use form post or restful API(ajax) to achieve your goal. – Terry Wei Commented Jun 5, 2018 at 7:24
  • 1 Also sanitise user inputs to prevent SQL injection. – Thum Choon Tat Commented Jun 5, 2018 at 7:25
  • 1 Please use prepared statements in your SQL or little kittens will die() – madflow Commented Jun 5, 2018 at 7:35
 |  Show 2 more ments

5 Answers 5

Reset to default 1

You should try to remove your PHP from your view if possible. If you move you PHP functions into a separate PHP file and call them with AJAX it will allow you to reuse the code on different pages if required.

This is not tested pletely but would be a cleaner solution I would say.

Add an id to you delete image:

<img id="delete" src="" title="delete"  alt="running test" style="width:15px;height:15px;border:0;margin-left:1cm" onclick="deleteProject()"/>

Change your javascript to use AJAX to call the PHP script:

$( document ).on( 'click', '#delete', function(){
    var r= confirm("Press a button!");
    if (r==true)
      {
        $.ajax({
        url: '<?php echo LOCATION_OF_PHP_SCRIPT; ?>',
        type: 'post',
        data: DATA_IF_NEEDED
        }).success( resp )
        {
            if( resp == TRUE )
          {
            alert( "Deleted" );
          }

        }
      }
    else
      {
        alert("You pressed Cancel!");              

      }
})

You will need to adjust some of the parameters to suit your application but should get you going.

on clicking the div the function read will execute and give hi

<?php
function read($id){
   echo $id;
  }
?>


<div onclick="<?php read("hi"); ?>" class="item">

</div>

Just follow this code to achieve using jQuery ajax call. This is the HTML code with jQuery included and I've used test.php file in the same directory. Just write your PHP function in test.php file. Finally the response will be displayed in the given div after the user pressed confirm.

<!DOCTYPE html>
<html>
<head>
    <title>Jquery ajax</title>
    <script src="https://ajax.googleapis./ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
    <button onclick="myFun()">Click me</button>
    <div id="div1"></div>
    <script>
        function myFun(){
            var r= confirm("Press a button!");
        if (r==true)
          {
            $.ajax({url: "test.php", success: function(result){
            $("#div1").html(result);
            }});  
          }
        else
          {
            alert("You pressed Cancel!");              

          }
        }
    </script>   
</body>
</html>

You can't run php code from JavaScript. JavaScript is client-side and php is server-side.

You have to create a script deleteThings.php that delete what you want and call it from client's JavaScript using asynchronous Ajax request.

For asynchronous Ajax request you can use jQuery, vanilla JavaScript, or others libraries.

Use ajax for calling PHP function from JAVASCRIPT function.

Check the below code.

$.ajax({

type: "POST",

url: 'your_functions.php',

dataType: 'json',

data: {functionname: 'delete'},

success: function (obj, textstatus) {
       }

})

your_functions.php

发布评论

评论列表(0)

  1. 暂无评论