开发者

AJAX call returns false when I expect true

I'm doing an ajax call in a code igniter application. The JS code is the following:

function removeGuest(guestID)
{
    if(confirm("Are you sure you want to delete this guest and his preferences?"))
    {
        $.ajax({
            type: "POST",
            url: "/event/ajax_delete_guest",
            data: { guestID: guestID },
            success: function(data)
            {
                console.log(data);
            }
        });
    }
}

This gets send to my controller:

public function ajax_delete_guest()
{
    if($this->input->post(开发者_如何学Go'guestID'))
    {
        $guestID = $this->input->post('guestID');
        if($this->events_model->delete_guest($guestID))
        {
            header('Content-type: application/json');
            echo json_encode(TRUE); 
        }
        else
        {
            header('Content-type: application/json');
            echo json_encode(FALSE);            
        }
    }
}

and my model:

public function delete_guest($guestID)
{
    $tables = array('event_guest', 'event_guest_prefs', 'event_guest_hotel');
    $this->db->where('guestID', $guestID);
    if($this->db->delete($tables))
    {
        return TRUE;
    }
    else
    {
        return FALSE;
    }
}

When removing a guest in the DB, it returns false in the console.log(). However, I'm fairly sure I'm making it return true when the deletion is successful. Anyone have any idea? I'm breaking my head over this. Thanks.


Have you tried adding die()?I once had the same problem and this solved it.

   if($this->events_model->delete_guest($guestID))
    {
        header('Content-type: application/json');
        echo json_encode(TRUE);
        die(); 
    }
    else
    {
        header('Content-type: application/json');
        echo json_encode(FALSE);            
        die();
    }


This fixed it:

public function delete_guest($guestID)
{
    $tables = array('event_guest_prefs', 'event_guest_hotel');
    $this->db->where('guestID', $guestID);
    if($this->db->delete('event_guest'))
    {
        $this->db->where('guestID', $guestID)->delete($tables);
        return TRUE;
    }
    else
    {
        return FALSE;
    }

Because the prefs and hotel tables aren't necessarily containing data for the $guestID, the original check returned false. The _guest table always contains data though, so I just check on that now and if it succeeds, I continue to delete the other tables. }

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜