another user
another user

Reputation: 93

Ajax success function doesn't work second time

I have made a form submit with AJAX, the first time it submits, it has the success function, however the second time it prints the success data in accept_friend.php instead of the #requests_container, like a normal PHP form.

$('.accept_friend').submit(function(){
    var data = $(this).serialize();

    $.ajax({
        url: "../accept_friend.php",
        type: "POST",
        data: data,
        success: function( data )
        {   
            $('#requests_container').html(data);
        },
        error: function(){
            alert('ERROR');
        }
    });

    return false;
});

here is accept_friend.php

<?php

session_start();

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require "classes/class.requests.php";
require "classes/db_config.php";

$current_user = $_POST['current_user'];
$friend_id = $_POST['friends_id'];

$requests = new Requests($DB_con);
if($_SERVER["REQUEST_METHOD"] == "POST"){
     $requests->accept($current_user, $friend_id);
}
?>

Upvotes: 2

Views: 807

Answers (2)

codisfy
codisfy

Reputation: 2183

It seems that you are replacing the entire html in your $('#requests_container') and I am assuming that the .accept_friend button is also inside the same container.

If this is the case then try replacing your code with

$('#requests_container').on('submit', '.accept_friend', function(){
    var data = $(this).serialize();

    $.ajax({
        url: "../accept_friend.php",
        type: "POST",
        data: data,
        success: function( data )
        {   
            $('#requests_container').html(data);
        },
        error: function(){
            alert('ERROR');
        }
    });

    return false;
});

This will keep your event alive even after the form button is removed and put back in the DOM

Upvotes: 1

Jaromanda X
Jaromanda X

Reputation: 1

I've tested this and it does work for me (Firefox)

after you've clobbered your form, rebind the submit event to the submitter function

$('.accept_friend').submit(function submitter() {
    var data = $(this).serialize();

    $.ajax({
        url: "../accept_friend.php",
        type: "POST",
        data: data,
        success: function(data) {   
            $('#requests_container').html(data);
            setTimeout(function() { // may not be needed
                $('.accept_friend').submit(submitter); // rebind submit
            }, 0);
        },
        error: function(){
            alert('ERROR');
        }
    });

    return false;
});

Upvotes: 0

Related Questions