Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Here are the steps to use CodeIgniter Ajax to display an error message when sending an email response:

  1. Create an AJAX function in your controller that will handle the sending of the email and return a JSON response. Example:
public function send_email() {
   $this->load->library('email');
   $this->email->from('your@example.com', 'Your Name');
   $this->email->to('recipient@example.com');
   $this->email->subject('Email Subject');
   $this->email->message('Email Message');

   if($this->email->send()) {
      $response['status'] = 'success';
   } else {
      $response['status'] = 'error';
      $response['message'] = $this->email->print_debugger();
   }
   echo json_encode($response);
}
  1. In your view, add a form with appropriate fields for email information and a submit button.

  2. Add a script to the view that will handle the form submission and display a message based on the AJAX response. Example:

$(document).ready(function(){
   $('#email-form').on('submit', function(e){
      e.preventDefault();
      var formData = $(this).serialize();

      $.ajax({
         url: '<?php echo base_url('email/send_email'); ?>',
         type: 'POST',
         dataType: 'json',
         data: formData,
         success: function(response){
            if (response.status == 'success') {
               alert('Email sent successfully!');
            } else {
               alert('Error sending email: ' + response.message);
            }
         },
         error: function(){
            alert('Error sending email. Please try again later.');
         }
      });
   });
});
  1. Replace the URL in the AJAX request with the appropriate URL for your controller function.

  2. Style the error message appropriately in your CSS.