开发者

ajax POST not working, can't figure why

I have a simple AJAX function to send an id of an object to a php page

My function looks like this:

$(function(){      
    $("a.vote").click(function(){
        //get the id
        the_id = $(this).attr('id');
        alert(the_id);

        //ajax post
        $.ajax({
            type: "POST",
            data: "?id="+the_id,
            url: "vote.php",
            success: function(msg)
            {
                $("span#message"+the_id).html(msg);
            }
        });
    });
});

My vote.php looks like this:

session_start();
if(isset($_SESSION['user'])) {
    // db setup removed

    // insert vote into db
    $q = "UPDATE votes SET vote = vote + 1 WHERE id = " . $_POST['id'];   
mysql_query($q);      
echo "You sent " . $_POST['id'];
}

When I execute my AJAX function, it appears that the vote.php is never run

I know that my AJAX function is being called correctly, because alert(the_id); is popping up with the correct ID.

I know my vote.php is functioning correctly because I can run an HTML method="post" with a textbox named "id", and it will update the database correctly.

Can anyone see what's wrong?

Thank y开发者_StackOverflow社区ou


You're trying to send your variables in the URL, not as POST variables. Should be something like:

$(function(){      
    $("a.vote").click(function(){
        //get the id
        var the_id = $(this).attr('id');
        alert(the_id);

        //ajax post
        $.ajax({
            type: "POST",
            data: {id:the_id},
            url: "vote.php",
            success: function(msg)
            {
                $("span#message"+the_id).html(msg);
            }
        });
    });
});

Your data should be as included as an object, not as a string URL. Check out the examples on the jquery API page for more info on this!


The principal thing I see in your code that doesn't look right is data: "?id="+the_id,. The ? is unnecessary, and illogical for a post request. Do the following instead:

data: {
    id: the_id
}

This lets jQuery do the URL-encoding for you.

As an additional point, you do $(this).attr(id). This is very inefficient. Do this.id instead, for exactly the same effect hundreds of times quicker at least 20 times quicker.


Your data value shouldn't need a question mark at the beginning.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜