简体   繁体   English

如果我在1个php文件中有2个函数,如何告诉ajax向哪个函数发送POST?

[英]If I have 2 functions in 1 php file, how to tell ajax to which function to send the POST?

I have 2 functions in 1 php file, one for upvote and 1 for downvote. 我在1个php文件中有2个函数,其中1个用于upvote,1个用于downvote。 How to tell ajax to post to the function with name upvoteImage()? 如何告诉ajax以名称upvoteImage()发布到函数? I'm literally starting out with ajax so I'm having some troubles figuring things out. 我实际上是从ajax开始的,所以在解决问题时遇到了一些麻烦。

Javascript file Javascript文件

$('.arrowUp').click(function(){
        var id = $("input[name='id']").val();
        var userId = $("input[name='userId']").val();
        $.post('../includes/voting.inc.php', {id: id, userId: userId}, function(data){
            alert(data);
        });

    });

PHP file PHP文件

function upvoteImage($conn) {
        if (isset($_POST['upvoteImage'])){

            $imageId = $_POST['id'];
            $userId = $_POST['userId'];

            $sql3 = "SELECT * FROM votingconnection WHERE userId='".$userId."' and imageId='".$imageId."'";
            $result3 = mysqli_query($conn, $sql3);
            $getResult3 = mysqli_fetch_assoc($result3);

            if ($getResult3['vote'] == 'downvote') {

                $sql4 = "UPDATE votingconnection SET vote='upvote' WHERE userId='".$userId."' and imageId='".$imageId."'";
                $result4 = mysqli_query($conn, $sql4);

                $sql5 = "UPDATE image SET upvotes = upvotes + 1 WHERE id='$imageId'";
                $result5 = mysqli_query($conn, $sql5);

                $sql6 = "UPDATE image SET downvotes = downvotes - 1 WHERE id='$imageId'";
                $result6 = mysqli_query($conn, $sql6);

                header("Location: ../index.php");

            } else {

            $sql = "INSERT INTO votingconnection (userId, imageId, vote) VALUES ('".$userId."','".$imageId."', 'upvote')";
            $result = mysqli_query($conn, $sql);

            $sql2 = "UPDATE image SET upvotes = upvotes + 1 WHERE id='$imageId'";
            $result2 = mysqli_query($conn, $sql2);

            header("Location: ../index.php");

        }

        }
    }

I just can't understand how to connect the index page, the page with the logic for upvote/downvote and the javascript page. 我只是不明白如何连接索引页面,具有upvote / downvote逻辑的页面以及javascript页面。 This is part of my index page. 这是我的索引页面的一部分。

<?php

    if (isset($_POST['action']) && in_array($_POST['action'], ['upvote', 'downvote'])) {
        if ($_POST['action'] == 'upvote' ) {
            upvoteImage($conn);
        } else {
            downvoteImage($conn);
        }
    }

    $currentUser = $_SESSION['id'];

    $sql = "SELECT * FROM image"; 
    $result = mysqli_query($conn, $sql);
    $getResult = mysqli_fetch_assoc($result);

    $numberOfResults = mysqli_num_rows($result);
    $resultsPerPage = 5;
    $numberOfPages = ceil($numberOfResults/$resultsPerPage);

    if (!isset($_GET['page'])) {
        $page = 1;
    } else {
        $page = $_GET['page'];
    }

    $currentPageResults = ($page-1)*$resultsPerPage;

    $sql2 = "SELECT * FROM image ORDER BY id DESC LIMIT ".$currentPageResults.','.$resultsPerPage;
    $result2 = mysqli_query($conn, $sql2);

    while($row = $result2->fetch_assoc()) { 

        $sql3 = "SELECT * FROM votingconnection WHERE userId='".$currentUser."' and imageId='".$row['id']."'";
        $result3 = mysqli_query($conn, $sql3);
        $getResult3 = mysqli_fetch_assoc($result3);
        $hasVoted = mysqli_num_rows($result3);
        $vote = $getResult3['vote'];

        echo    "<div class='imageContainer'>" 
                ."<h1>".$row["name"].'</h1>' 
                .'<div class="stickyImageContainer"><a href="imageInfo.php?image='.$row["path"].'"><img class="uploadedImg" src="uploads/'.$row["path"] .'" alt="Random image" /></a> ';
        if (isset($_SESSION['id'])) {
        if ($hasVoted < 1) {
            echo    "<div class='upvoteDownvoteRatingContainer'><form class='upvoteImage' method='POST' action=''>
                        <input type='hidden' name='action' value='upvote'>
                        <input type='hidden' name='id' value='".$row['id']."'>
                        <input type='hidden' name='userId' value='".$currentUser."'>
                        <button class='upvoteImageButton' type='submit' name='upvoteImage'><img class='arrowUp' src='../images/Social Media/arrowUp.png' alt='submit'></button>
                    </form>";

            echo "<div class='ratingNumber'>";
                if ($row['upvotes'] - $row['downvotes'] <= 0) {
                    echo "<p>0</p>";
                } else {
                    echo $row['upvotes'] - $row['downvotes'];
                }

            echo "</div>";

            echo    "<form class='downvoteImage' method='POST' action=''>
                        <input type='hidden' name='action' value='downvote'>
                        <input type='hidden' name='id' value='".$row['id']."'>
                        <input type='hidden' name='userId' value='".$currentUser."'>
                        <button class='downvoteImageButton' type='submit' name='downvoteImage'><img class='arrowDown' src='../images/Social Media/arrowDown.png' alt='submit'></button>
                    </form></div>";
        }

Ajax is not "posting to a function", it's only a way to request a page from the server. Ajax不是“发布到函数”,它只是从服务器请求页面的一种方式。

The code in your page is the one that should decide what to do, so basically you can just call the function in your page: 页面中的代码是应该决定执行该操作的代码,因此基本上,您可以只调用页面中的函数:

function upvoteImage() {
    ....
}
upvoteImage()

Of check the data you got from the client, and based on that data - run the relevant function: 检查从客户端获取的数据,并基于该数据-运行相关功能:

function upvoteImage() {
    ....
}
if ($_POST['do_upvote']) {
    upvoteImage()
}

您可以通过发送带有诸如"type:"upvote""type:"downvote"标签的帖子数据来调用函数,然后在php中,根据该标签调用函数upvoteImage或doenVoteImage。

You don't tell ajax to post to a function specifically. 您无需告诉ajax具体发布到函数。 Instead tell ajax to post to a file specifically. 而是告诉ajax具体发布到文件中。

$('.arrowUp').click(function(){
    var id = $("input[name='id']").val();
    var userId = $("input[name='userId']").val();
    $.post('../includes/upvote.inc.php', {id: id, userId: userId}, function(data){
        alert(data);
    });

});

$('.arrowDown').click(function(){
    var id = $("input[name='id']").val();
    var userId = $("input[name='userId']").val();
    $.post('../includes/downvote.inc.php', {id: id, userId: userId}, function(data){
        alert(data);
    });

});

One for handling the upvote, and the other the downvote. 一个用于处理赞成票,另一个用于处理表决票。

Either send the preferred action (upvote or downvote) along with the query part of the URL, or send a separate action data(upvote or downvote) along with id and userId . 发送首选操作 (upvote或downvote)以及URL的查询部分,或者发送单独的动作数据(upvote或downvote)以及iduserId

Method(1): 方法(1):

// for downvote, URL would be ../includes/voting.inc.php?action=downvote
$.post('../includes/voting.inc.php?action=upvote', {id: id, userId: userId}, function(data){
    alert(data);
});

And process the request in voting.inc.php page the following way, 并按照以下方式在voting.inc.php页面中处理请求,

if($_GET['action'] == "upvote"){
    // call upvoteImage function
}else if($_GET['action'] == "downvote"){
    // call downvoteImage function
}

Method(2): 方法(2):

// for downvote, {id: id, userId: userId, action: 'downvote'}
$.post('../includes/voting.inc.php', {id: id, userId: userId, action: 'upvote'}, function(data){
    alert(data);
});

And process the request in voting.inc.php page the following way, 并按照以下方式在voting.inc.php页面中处理请求,

if($_POST['action'] == "upvote"){
    // call upvoteImage function
}else if($_POST['action'] == "downvote"){
    // call downvoteImage function
}

You can simply do this via data-* attribute and make your voting buttons like this 您可以简单地通过data-*属性来执行此操作,并使投票按钮像这样

<button class="vote" data-type="up" data-id="1" data-user-id="2">Up</button>
<button class="vote" data-type="down" data-id="1" data-user-id="2">Down</button>

then you can simply send the ajax request like this 然后您可以像这样简单地发送ajax请求

$('.vote').click(function() {
    var data = {
        id:     $(this).data('id'),
        userId: $(this).data('user-id'),
        type:   $(this).data('type')
    };

    $.post('../includes/voting.inc.php', data, function(data){
        alert(data);
    });
});

Finally, in your server side you can check the type and call functions 最后,在服务器端,您可以检查type和调用函数

if (isset($_POST['type']) && $_POST['type'] == "up"){
    // Call upvote function here
}
else if (isset($_POST['type']) && $_POST['type'] == "down"){
    // Call downvote function here
}
else {
    // Abort if invalid
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我有一个用RIFF编码的文件。 如何通过ajax发布响应发送此文件? - I have a file that is encoded in RIFF. How can I send this file through an ajax post response? 如何使用符号(+,*,/, - )发送包含php源的帖子数据,并使用ajax请求将该数据写入文件? - How to send post data which contains php source with symbols like (+, *, /, -) and writing that data to a file using ajax request? 如何使用jquery ajax将POST数据发送到PHP函数 - how to send POST data with jquery ajax to PHP function Facebook-如何通过Ajax POST将用户ID数组发送到PHP文件 - Facebook - How to send an array of User IDs to a PHP file by Ajax POST 如何-我的时间和日期格式有一个js,我希望它添加到我的ajax帖子中并发送到php - How to - I have a js for my time&date format and I want it to add to my ajax post and send to php 将AJAX中的post变量发送到PHP文件以获取可变性 - Send post variable in AJAX to PHP file for varaible 发送一个PHP + AJAX的帖子 - Send a post with PHP + AJAX 如何用 AJAX 告诉 PHP 在文章下显示哪些评论? - How to tell PHP which comments to show under the article with AJAX? 将数据从AJAX函数发送到PHP文件 - Send data from AJAX function to PHP file 如何通过$ .ajax()将JavaScript变量发送到PHP文件中 - How do I send a JavaScript variable into a PHP file via $.ajax()
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM