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

Twiebie
#1 2013-08-17 14:51

I'm wondering what in Cotonti the best way is to handle errors with an Ajax submitted form to a PHP file.

Normally with a simple form the errors can be handled with Cotonti's cot_error(); function like this:

PHP
1
2
cot_error('someErrorMessage', '');
cot_redirect(cot_url('myPlug', 'm=form', '', true));

How would you guys handle something like this if the form is submitted with Ajax?

Trustmaster
#2 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!
Twiebie
#3 2013-08-18 00:33

Thanks, Trustmaster! Looks like I sort of was on the right track with my JSON response effort.

I'm guessing you are using this with success: function() {}, as you return 200 regardless?

Trustmaster
#4 2013-08-18 06:25

Yes, I check the status and error messages in success function.

May the Source be with you!
Twiebie
#5 2013-08-18 10:05

OK, got it.

Thanks!