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


Ajax Listen Event on a Button Click then Runs a Php file

如果按钮被点击,我需要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);
}
?>

尝试重写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" />

Fiddle演示:http://jsfiddle.net/sbybd/

ajax调用示例:

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