post ajax data to PHP and return data

前端 未结 3 2030
攒了一身酷
攒了一身酷 2020-12-08 23:06

How can i post some ajax data to the controller function and get it back? For I want to post one integer to the function, and get another integer (total votes for the item w

相关标签:
3条回答
  • 2020-12-08 23:40
     $.ajax({
                type: "POST",
                data: {data:the_id},
                url: "http://localhost/test/index.php/data/count_votes",
                success: function(data){
                   //data will contain the vote count echoed by the controller i.e.  
                     "yourVoteCount"
                  //then append the result where ever you want like
                  $("span#votes_number").html(data); //data will be containing the vote count which you have echoed from the controller
    
                    }
                });
    

    in the controller

    $data = $_POST['data'];  //$data will contain the_id
    //do some processing
    echo "yourVoteCount";
    

    Clarification

    i think you are confusing

    {data:the_id}
    

    with

    success:function(data){
    

    both the data are different for your own clarity sake you can modify it as

    success:function(vote_count){
    $(span#someId).html(vote_count);
    
    0 讨论(0)
  • 2020-12-08 23:41

    So what does count_votes look like? Is it a script? Anything that you want to get back from an ajax call can be retrieved using a simple echo (of course you could use JSON or xml, but for this simple example you would just need to output something in count_votes.php like:

    $id = $_POST['id'];
    
    function getVotes($id){
        // call your database here
        $query = ("SELECT votes FROM poll WHERE ID = $id");
        $result = @mysql_query($query);
        $row = mysql_fetch_row($result);
    
        return $row->votes;
    }
    $votes = getVotes($id);
    echo $votes;
    

    This is just pseudocode, but should give you the idea. What ever you echo from count_votes will be what is returned to "data" in your ajax call.

    0 讨论(0)
  • 2020-12-08 23:45

    For the JS, try

    data: {id: the_id}
    ...
    success: function(data) {
            alert('the server returned ' + data;
        }
    

    and

    $the_id = intval($_POST['id']);
    

    in PHP

    0 讨论(0)
提交回复
热议问题