用ajax和Json发布简单的表单

时间:2013-12-15 19:49:13

标签: php jquery ajax json

我正在尝试使用Ajax和json工作的表单,但似乎无法解决它:( 如果有人可以帮忙,我真的很感激!正在阅读这么多不同的教程,但没有做对。

  • 在我的index.php中,我有一个只有一个图像作为按钮的表单。

  • 然后在另一个文件(allFunctions.php)中我有一个类。在那个类中,我有一个名为的函数 giveCandy()已连接到按钮。

  • 然后我有一个js文件,我现在正试图使用​​它。但是当我点击按钮时页面仍会刷新,我打印出值true

更新:页面刷新仍有问题...

index.php文件:

<form action="index.php" method="POST"> 
<input type="hidden" name="candy" />
<input type="image" id="button_candy" class="four columns" src="views/img/candy.png"/>
</form>

然后在我的函数文件中:

function giveCandy ()
    {
        if ( isset($_POST['candy']))
        {   

        $db = Database::getInstance();
        $classUser = new user();
        $userId = $classUser->getUserData($_SESSION['id']);
        $user = $userId['id'];

        $candyPiece = 10;

        $query = $db->prepare("SELECT fullness, lastfed FROM userdata WHERE id = ?");
        $query->bindValue(1, $user);

        $query->execute();
        $data = $query->fetch();

        $newFullness = $candyPiece + $data['fullness'];

        try
            {
        $query = $db->prepare("UPDATE userdata SET fullness = $newFullness, lastfed = CURRENT_TIMESTAMP WHERE id = ?");
        $query->bindValue(1, $user);

        $query->execute();
        //$this->calculateFullness();
        echo json_encode($query);
            }
        catch (PDOException $e)
            {
                echo 'Sorry iti could not eat at this time';        
            }
        }
    }

然后是js文件:

$(document).ready(function () {
    $('#button_candy').click(function (event) {
        event.preventDefault();
        $.ajax({
            url: 'index.php',
            method: 'POST',
            data: $(this).serialize(), // your formdata (this refers to the form element)
            dataType: 'json',
            success: function (data) { // data is what your allFunctions.php php echos
                $('#query').fadeOut(function () {
                    $('#query').html(data).fadeIn();
                });
                console.log('Ajax request returned successfully.');
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.log('Ajax request failed: ' + textStatus + ', ' + errorThrown);
            },
        });
    });
});

1 个答案:

答案 0 :(得分:0)

allFunctions.php:

if ($_POST['candy']) {
    allFunctions::giveCandy();
}

class allFunctions {

    static function giveCandy ()
    { 
        $db = Database::getInstance();
        // ....

JS:

$(document).ready(function () {
    $('#button_candy').submit(function (event) {
        event.preventDefault();
        $.ajax({
            url: '../model/allFunctions.php',
            method: 'POST',
            data: $(this).serialize(), // your formdata (this refers to the form element)
            dataType: 'json',
            success: function (data) { // data is what your allFunctions.php php echos
                $('#result').fadeOut(function () {
                    $('#result').html(data).fadeIn();
                });
                console.log('Ajax request returned successfully.');
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.log('Ajax request failed: ' + textStatus + ', ' + errorThrown);
            },
        });
    });
});