Ask Your Question
0

How can CodeIgniter Ajax be used to display an error message when sending an email response?

asked 2023-06-22 20:26:54 +0000

pufferfish gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-06-22 20:40:01 +0000

plato gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-22 20:26:54 +0000

Seen: 10 times

Last updated: Jun 22 '23