dongwuqi4243 2012-05-03 08:48
浏览 50
已采纳

jquery ajax成功函数只能工作一次

I'm trying to implement a form that utilizes jquery's post feature to dynamically update the database. What I'm realizing is that after the user clicks the "update" button, the success function is called back just fine with a "Update successful" message.

The issue I have for the stackoverflow world is why on subsequent clicks (w/o refreshing the page) I'm not getting this same success message. Also, ironically my database is being updated, so I know the AJAX call is going through.

I've posted my code below:

JS

var TEAM = { 
update: function() {

    var form_data = $('form').serialize();
    $.ajax({
        type: "POST",
        url: "../manager/edit_team.php",
        data: form_data,
        error: function() {
            $('#status').text('Update failed. Try again.').slideDown('slow');
        },
        success: function() {
            $('#status').text('Update successful!');
        },
        complete: function() { 
            setTimeout(function() {
                $('#status').slideUp('slow');
                }, 3000);
        },
        cache: false
    });
}
}

// jQuery Code for when page is loaded
$(document).ready(function()
{
 $("#update").on("click", function() {
     TEAM.update();
 });
 });

PHP (I welcome any other comments as well)

require '../includes/config.php';
include '../includes/header.html';

// autoloading of classes
function __autoload($class) {
    require_once('../classes/' . $class . '.php');
}

// Site access level -> Manager
$lvl = 'M'; 

// Assign user object from session variable
if (isset($_SESSION['userObj']))
{
    $manager = $_SESSION['userObj'];
}
else 
{
    session_unset();
    session_destroy();
    $url = BASE_URL . 'index.php';
    ob_end_clean();
    header("Location: $url");
    exit(); 
}

// Establish database connection
require_once MYSQL2;

// Assign Database Resource to object
$manager->setDB($db);

// Authorized Login Check
if (!$manager->valid($lvl))
{
    session_unset();
    session_destroy();
    $url = BASE_URL . 'index.php';
    ob_end_clean();
    header("Location: $url");
    exit(); 
}

// Check for a valid game sch ID, through GET or POST:
if ( (isset($_GET['z'])) && (is_numeric($_GET['z'])) )
{
    // Point A in Code Flow
    // Assign variable from myteams-m.php using GET method
    $id = $_GET['z'];
}
elseif ( (isset($_POST['z'])) && (is_numeric($_POST['z'])) )
{
    // Point C in Code Flow
    // Assign variable from edit_team.php FORM submission (hidden id field)
    $id = $_POST['z'];
}
else 
{
    // No valid ID, kill the script.
    echo '<p class="error">This page has been accessed in error.</p>';
    include '../includes/footer.html';
    exit();
}

$team = new ManagerTeam();
$team->setDB($db);
$team->setTeamID($id);
$team->pullTeamData();

$flag = 0;
echo $flag . "<br />";
// Confirmation that form has been submitted:   
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{   // Point D in Code Flow

    // Assume invalid values:
    $tname = FALSE;

    // Validate team name
    if ($_POST['tname'])
    {
        $tname = $_POST['tname'];

    }
    else 
    {
        echo '<p class="error"> Please enter a team name.</p>';
    }       

    // Validate about team information
    if ($_POST['abouttm'])
    {
        $abtm = trim($_POST['abouttm']);

    }
    else 
    {
        $abtm = '';
    }

    // Check if user entered information is valid before continuing to edit game
    if ($tname)
    {
        if($team->editTeam($tname, $abtm) == True)
        {
            echo '<p>Team was successfully updated</p>';
            $flag = 1;
        }
        else 
        {
            echo '<p>No changes were made</p>';
            $flag = 2;
        }
    }
    else
    {   // Errors in the user entered information
        echo '<p class="error">Please try again.</p>';
    }

}   // End of submit conditional.
echo $flag . "<br />";
// Point B in Code Flow
// Always show the form...

// Get team name attribute
$team->pullTeamData();
$teamname = $team->getTeamAttribute('tmname');
$about = $team->getTeamAttribute('about');

if ($teamname != '') // Valid user ID, show the form.   
{
    // Headliner
    echo '<h2>Edit Team</h2>';

    // Create the form:
    echo '
    <div id="EditTeam"></div>
    <div id="Team">
        <fieldset id="TeamDetails">
            <legend>Edit Team</legend>
            <form method="post" id="information">
            <p id="status"></p>
            <input type="hidden" name="z" value="' . $id . '" />                
            <p>
                <label for="tname">New Team Name:</label><br/>
                <input type="text" name="tname" id="tname" size="10" maxlength="45" value="' . $teamname . '" />
            </p>
            <p>
                <label for="abouttm">Team Information:</label><br/>
                <textarea id="abouttm" name="abouttm" cols="30" rows="2">"' . $about . '"</textarea><br />
                <small>Enter something cool about your team.</small>
            </p>
            <p>
                <input type="hidden" name="id" id="id">
                <input type="button" value="update" id="update" />
            </p>
        </form>
        </fieldset>
    </div>';                

}
else 
{   //Not a valid user ID, kill the script
    echo '<p class="error">This page has been accessed in error.</p>';
    include '../includes/footer.html';
    exit();
}   

// Close the connection:
$db->close();
unset($db);

include '../includes/footer.html';
?>

You'll notice I also have a $flag defined to help with the debugging, but ironically it outputs 0 no matter the number of clicks to the "update" button. So there's no indication that the database is being updated, yet when I check the tables it certainly is.

I appreciate any help or pointers. Thanks,

  • 写回答

1条回答 默认 最新

  • douyiji3919 2012-05-03 09:08
    关注

    #status message is not showing because you've hidden it by slideUp(), to show it again you need to slideDown() them.

        success: function() {
            $('#status').text('Update successful!');
    -ADD->  $('#status').slideDown('slow');
        },
        complete: function() { 
            setTimeout(function() {
                $('#status').slideUp('slow');
                }, 3000);
    

    Do it same way as you have done in error handler:
    success: function(){
    $('#status').text('Update successful!').slideDown('slow');
    ...

    It seems that you know it already and just forgot it...

    Other method that may be useful is stop() to make sure that previous animation is stopped when new one is starting., especially important when using long timeouts/animations.
    (useful = can prevent other problems with visibility and makes sure that messages does not start jumping in and out)
    (long = somewhere around 0,5-1,5 sec or more, if during this time can happen something else then it is long...)

    For example, this will clear fx queue, finish running animation immediately and slideUp():

    $('#status').stop(true, true).slideUp('slow');
    

    You also asked suggestions for other parts of code

    If you are using same code at least twice or if it is general method that could be reused make it reusable:

    function redirect_to( $page ) {
        session_unset();
        session_destroy();
        $url = BASE_URL . $page;
        ob_end_clean();
        header("Location: $url");
        exit(); 
    }
    
    if ($condition == true) {
        redirect_to( 'index.php' );`
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)