Wilcovanmeppelen Wilcovanmeppelen - 7 months ago 11
Javascript Question

How to return a ajax error?

I want to show a ajax error after submitting a form. It ends now with 'die'
but what is the best way to handle this? Just write something in this php file in 'script' tags?

if($_POST['postForm'] == 'newsletter'){

$newsletterSubscriber = new NewsletterSubscriber();
$newsletterSubscriber->set('CMS_newsletters_id', 2);
$newsletterSubscriber->set('created', date('Y-m-d H:i:s'));
$newsletterSubscriber->set('firstName', $_POST['voornaam']);
$newsletterSubscriber->set('lastName', $_POST['achternaam']);
$newsletterSubscriber->set('companyName', $_POST['beddrijfsnaam']);
$newsletterSubscriber->set('emailAddress', $_POST['email']);
$newsletterSubscriber->set('subscribed', 1);
$saved = $newsletterSubscriber->save();

die('subscriber added');
}


I tried several solutions I found but I can't get it to work.

Thanks!

Answer

All you need to do is create a array and place any parameters you want to pass back into that array, then use json_encode() to turn it into a json string that can be easily processed by javascript

if($_POST['postForm'] == 'newsletter'){

    $newsletterSubscriber = new NewsletterSubscriber();
    $newsletterSubscriber->set('CMS_newsletters_id', 2);
    $newsletterSubscriber->set('created', date('Y-m-d H:i:s'));
    $newsletterSubscriber->set('firstName', $_POST['voornaam']);
    $newsletterSubscriber->set('lastName', $_POST['achternaam']);
    $newsletterSubscriber->set('companyName', $_POST['beddrijfsnaam']);
    $newsletterSubscriber->set('emailAddress', $_POST['email']);
    $newsletterSubscriber->set('subscribed', 1);
    $saved = $newsletterSubscriber->save();

    $response = array('error_code'=>0, 
                      'message'=>'subscriber added'
                     );
    echo json_encode($response);
    exit;
}

The javascript woudl be something like

$.ajax({
    type: "POST",
    url: "connection.php",
    data: {param1: 'aaa'},
    dataType: JSON
})
.done( function(data){
        if(data.error_code == 0) {
           alert(data.message);
        }
    }
});

Note when you use dataType:JSON the browser automatically converts the json string returned to a javascript object so you can address data.error_code and data.message in simple javascript object notation