如何用href调用函数?

时间:2017-06-08 01:47:22

标签: javascript php jquery

我正在尝试将某个函数调用hreffunction位于functions.php 我的href位于views/something.php

所以,这是我的功能:

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

我的link button位于<li>(不是表单):

<?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; ?>

(不要注意foreach)

1 个答案:

答案 0 :(得分:1)

您需要更改此选项以使用ajax调用或表单发布来调用PHP函数。

这是一个非常基本的例子,它应该指向正确的方向

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,假设$notu[0]包含用户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,需要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;
}