duanli12176 2017-06-08 01:47
浏览 451

如何用href调用函数?

I´m trying to call a function into a href, my function is on functions.php and my href is on views/something.php

so, this is my function:

function discount($connection, $us){
    $discount = $conexion->prepare("UPDATE postule SET seen = 1 WHERE id = $us");
    $discount->execute();
    return $discount;
}

and my link button is on an <li> (not in a form):

<?php foreach ($total_notu as $notu) : ?>
    <li><a onClick="<?php discount() ?>" href="notificaciones.php"> Notificaciones <span class="badge "><?php echo "$notu[0]"; ?></span></a></li>
  <?php endforeach; ?>

(Do not pay attention to the foreach)

  • 写回答

1条回答 默认 最新

  • dongshuo2752 2017-06-08 02:49
    关注

    You'll need to change this to use an ajax call or form post to call the PHP function.

    Here's a really basic example which should point you in the right direction

    discount.php

    <?php
    
        // Load $connection from somewhere
    
        // Get user, it's better to get this from a cookie or session rather than GET
        $user = $_GET['user']
    
        $discount = $connection->prepare("UPDATE postule SET seen = 1 WHERE id = :user");
        $discount->bindParam(':user', $user);
        $result = $discount->execute();
    
        // Throw error if something went wrong with the update, this will cause $.ajax to use the error function
        if (!$result) {
            http_response_code(500);
        }
    

    html, assuming $notu[0] contains the user id

    <?php foreach ($total_notu as $notu) : ?>
        <li><a onClick="return callDiscount('<?php echo "$notu[0]"; ?>');" href="#"> Notificaciones <span class="badge "><?php echo "$notu[0]"; ?></span></a></li>
    <?php endforeach; ?>
    

    js, requires jquery

    function callDiscount(user_id)
    {
        // Perform ajax call to discount.php
        $.ajax({
            url: '/discount.php?user=' + user_id, 
            error: function() {
                alert('An error occurred');
            },
            success: function(data) {
                // Redirect user to notificaciones.php
                document.location = '/notificaciones.php';
            }
        });
    
        // Prevent link click doing anything
        return false;
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改