skip to Main Content

Hi I’m having issue figuring out where did i get this wrong, for the delete function works well however, the error was fired even though JSON response returns success.

$(document).on('click', '.remove-btn', function() {
    var id = $(this).data('id');
    var confirmDelete = confirm("Are you sure you want to remove this User");

    formData = {
        'form_process' : 'Remove User',
        'id' : id,
    }

    if (confirmDelete) {
        $.ajax({
            type    : 'POST', 
            url     : 'library/page/process/remove_user.php', 
            data    : formData, 
            dataType: 'json',
            beforeSend: function(){
                window.scrollTo(0, 0);
                $("#loading-overlay").show();
            },
            success : function(data) {
                $("#loading-overlay").hide();
                if (!data.success) { 
                    danger ('Process Error', data.errors) 
                } else {
                    success ('Success', 'User has been removed successfully.');

                    setTimeout(function() {
                        window.location.href = window.parent.CloseDialog();
                    }, 3000);
                }
            },
            error : function (xhr, ajaxOptions, thrownError) {
                $("#loading-overlay").hide();
                danger ('Process Error', "There is unknown error occurs. Please contact administrator for system verification") 
                console.log(xhr.status);
                console.log(xhr.responseText);
                console.log(thrownError);
                console.log('There is unknown error occurs. Please contact administrator for system verification');
            }
        });
    }
})

And below is remove_user.php code

if($_POST['form_process'] == 'Remove User') {

    $training_info = $c_eta->_get_user_info($_POST['id']);

    if (count($training_info) > 0) {
        if ($c_eta->_remove_user($_POST['id'])) {
            $form_data['success'] = true;
        } else {
            $form_data['success'] = false;
            $form_data['errors'] = "Unable to remove user";
        }
        echo json_encode($form_data);
        return; 
    }
}

The json response is

{"success":true}

The user is deleted yet the message i keep getting is "Process Error', "There is unknown error occurs. Please contact administrator for system verification".

I tried adding header('Content-Type: application/json'); before echo json_encode($form_data); as suggested in one of the posts in here, however it does not work.

UPDATE:

Below are the logging values that was displayed in the browser console tab:

xhr.status = 200

xhr.responseText = 49{"success":true}

thrownError = SyntaxError: Unexpected non-whitespace character after JSON at position 4 (line 2 column 3)

I am not sure where did i get wrong in the syntax error but if I changed the datatype: text it will go here:

if (!data.success) { 
    danger ('Process Error', data.errors) 
}

with the message "Process Error", "Undefined".

UPDATE 2.0:

I figured the issue comes from the datatable where the delete button is situated at. Based on xhr.responseText = 49{"success":true} error i mentioned above, 49 is the id of the data to be deleted. It has appended itself to the json response. Below is my delete button code:

array(
    'db' => 'id',
    'dt' => 5,
    'tbl_field' => 'eta.id',
    'formatter' => function($d, $row) {
        $id = $d;
        $remove = '<a class="remove-btn" data-id="'.$id.'">' .
                '<img src="assets/img/delete.png" style="width:16px;height:16px;"></a>';
        return $remove;
})

Assuming the return of the $remove button results in the id being appended in the json response, I also tried changing my code as follows:

userDatatable.on('draw.dt', function() {
    $('#user_datatable').find('.remove-btn').remove(); 
    $('#user_datatable').find('tbody tr').each(function() {
        var id = $(this).find('td:eq(5)').text();  //row id
        var buttonHtml = '<a class="remove-btn" data-id="' + id + '"><img src="assets/img/delete.png" alt="Remove User" style="width:16px;height:16px;" title="Remove User"></a>';
        $(this).find('td:eq(5)').html(buttonHtml);
});

However, the id is still included in the response. Any idea?

2

Answers


  1. Chosen as BEST ANSWER

    I found the solution. I basically added

    ob_end_clean();
    flush();
    

    just before

    echo json_encode($form_data);
    exit;
    

    to fix the issue. Thanks everyone helping!


  2. You should send your response with all necessary headers, especially the response code.

    if($_POST['form_process'] == 'Remove User') {
    
        $training_info = $c_eta->_get_user_info($_POST['id']);
    
        if (count($training_info) > 0) {
            if ($c_eta->_remove_user($_POST['id'])) {
                $form_data['success'] = true;
            } else {
                $form_data['success'] = false;
                $form_data['errors'] = "Unable to remove user";
            }
    
    
            header("HTTP/1.1 200 OK");
            header("Content-Type: application/json"); 
    
            // Optionally you may decide to add CORS support
            header('Access-Control-Allow-Origin: *');
    
            echo json_encode($form_data);
            return; 
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search