按钮上的Ajax侦听事件单击然后运行Php文件

时间:2012-02-26 23:50:12

标签: php jquery html ajax button

如果单击按钮,我需要AJAX来监听。然后,如果它是我需要它来运行PHP脚本。由于AJAX没有正确地听按钮单击而我遇到了麻烦,所以它从不运行脚本 您可能会看到我的代码中的任何错误? 关于我应该如何做的任何建议?

按钮:

<input id="button_1" type="button" value="favorites1" onclick="favfunct();" />

调用它的AJAX是:(ajaxlisten.js

<script type="text/javascript">

    $(document).ready(function () { // Make sure the elements are loaded on the page
        // Listen for a click event on the button
        $('#button_1').click(favfunct);
    });

    function favfunct(e) {
        // Stop the page from "following" the button (ie. submitting the form)
        e.preventDefault();
        e.stopPropagation();

        // Call an AJAX function to the proper page
        $.ajax("js/addtofavorites.php", {
            // Pass our data to the server
            data: { "get" : "runfunction", "action" : "favorites1" },
            // Pass using the appropriate method
            method: "POST",
            // When the request is completed and successful, run this code.
            success: function (response) {
            // Successfully added to favorites. JS code goes here for this condition.
                alert ("successfully loaded")
            }          
        });
    }
</script>

Php文件(addtofavorites.php

<?php
$con = mysql_connect("localhost","root","student");

if ($_POST["action"] = 'favorites1')
{ 
    if (!$con);
    {
        die('Could not connect: ' . mysql_error());
    }                   
    mysql_select_db("tvid", $con);

    $sql="INSERT INTO tv (userid, favorites) VALUES (345,77);"
    if (!mysql_query($sql,$con));
    {
        die('Error: ' . mysql_error());
    }
    echo "Your Video was Added To Your Favorites";
    mysql_close($con);
}
?>

1 个答案:

答案 0 :(得分:1)

尝试重写click功能:

$(document).ready(function () { 
   $('#button_1').click(function(e){
        e.preventDefault();
        e.stopPropagation();
        favfunct();
   });
});

然后是favfunct

function favfunct() {
// AJAX Call Below
// rest of your code

那应该让你的favfunct正在运行。之后,如有必要,您可以进一步调试代码。

您也可以从按钮上取消onclick

<input id="button_1" type="button" value="favorites1" />

小提琴演示:http://jsfiddle.net/sbybd/

ajax电话的示例:

$.ajax({
     type: "POST",
     url: "js/addtofavorites.php",
     data: { "get" : "runfunction", "action" : "favorites1" },
     success: function (response) {
         alert ("successfully loaded");
     }    
 });