Run PHP code when user clicks link and pass variables

前端 未结 2 828
难免孤独
难免孤独 2021-01-25 05:37

I need to run a PHP code from external server when user clicks a link. Link can\'t lead directly to PHP file so I guess I need to use AJAX/jQuery to run the PHP? But how can I d

相关标签:
2条回答
  • 2021-01-25 06:05

    use something like this in you page with link

    Some text

    in the same page put this somewhere on top

    <script language='javascript'>
    $(function(){
    $('.myClass').click(function(){
    var data1 = 'someString';
    var data2 = 5;//some integer
    var data3 = "<?php echo $somephpVariable?>";
    
    $.ajax({
    
    url : "phpfile.php (where you want to pass datas or run some php code)",
    data: "d1="+data1+"&d2="+data2+"&d3="+data3,
    type : "post",//can be get or post
    success: function(){
            alert('success');//do something
        }
    
    });
    return false;
    });
    });
    
    </script>
    

    on the url mentioned in url: in ajax submission you can fetch those datas passed for examlple

    <?php
    $data1 =$_POST['d1'];
    $data2 =$_POST['d2'];
    $data3 =$_POST['d3'];
    //now you can perform actions as you wish
    ?>
    

    hope that helps

    0 讨论(0)
  • 2021-01-25 06:24

    You can do this with an ajax request too. The basic idea is:

    1. Send ajax request to runcode.html
    2. Configure another AJAX to trigger from that page

    Considering, this as the markup

    <a id="link" href="runcode.html'">Test</a>
    

    JS

    $("#link").on("click", function() {
        $.get("runcode.html", { "id" : ID }, function(data) {
           //on success 
        });
        return false; //stop the navigation 
    });
    
    0 讨论(0)
提交回复
热议问题