Forums / Craftwork / Server-side / Error handling with Ajax and PHP

Trustmaster
#37795 2013-08-17 18:00

Here is an example trick that I use:

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
    $rpost = post_import();
    if (post_validate($rpost, $_POST['name']))
    {
        post_send($rpost);
        $response = array(
            'status'  => true,
            'message' => $L['post_message_sent']
        );
    }
    else
    {
        // Return error messages
        $error_fields = array();
        $error_messages = array();
        foreach ($_SESSION['cot_messages'][$sys['site_id']] as $src => $grp)
        {
            $error_fields[] = $src;
            foreach ($grp as $msg)
            {
                $error_messages[] = isset($L[$msg['text']]) ? $L[$msg['text']] : $msg['text'];
            }
        }
        $response = array(
            'status'         => false,
            'error_fields'   => $error_fields,
            'error_messages' => $error_messages
        );
        cot_clear_messages();
    }
 
    cot_sendheaders('application/json', '200 OK');
 
    echo json_encode($response);
}

 

May the Source be with you!