php - How to return a ajax error? -
i want show ajax error after submitting form. ends 'die' best way handle this? write in 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 found can't work.
thanks!
all need create array , place parameters want pass array, use json_encode()
turn json string can processed 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 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 use datatype:json
browser automatically converts json string returned javascript object can address data.error_code
, data.message
in simple javascript object notation
Comments
Post a Comment