Jeeva Jeeva - 1 year ago 143
Ajax Question

How to return if email is sent successfully or error in Codeigniter AJAX

I want return a value back to ajax from controller if and when the email is sent. Below are some code.

In the Below code i want to set the flash data in session and it should set the either of the condition and call it back in AJAX


public function send_reply(){
$data = array(
'from_email' => "",
'recipient' => $this->input->post('recipient'),
'from_name' => "jeeva",
'subject' => $this->input->post('subject'),
'message' => $this->input->post('message'),

echo json_encode($data);

$this->email->from($data['from_email'], $data['from_name']);

//Send mail
if($this->email->send()) {
$this->session->set_flashdata("email_sent","<span> * Email sent successfully. </span> ");

} else {

$this->session->set_flashdata("email_sent","<span> * Error in sending Email.</span> ");
// $this->load->view('adminhp');


Ajax Code

// Ajax post for email sending
$(document).ready( function() {
$(".mailsub").click(function(event) {

var recipient = jQuery(this).closest('form').find('input.recipient').val();
var subject = jQuery(this).closest('form').find('input.subject').val();
var message = jQuery(this).closest('form').find('textarea.message').val();

type: "POST",
url: "<?php echo base_url(); ?>" + "index.php/user_authentication/send_reply",
dataType: 'json',
data: {recipient: recipient, subject: subject, message:message},
success: function(result) {
if (result)
// Show Entered Value
jQuery("div#rslt").html("Sent Successfully");


I want to set it the flash data in below code

echo "<br/>";
echo "<div id='result' style='display: none'>";
echo "<div id='rslt' style='display:inline'></div>";
// echo $this->session->flashdata('email_sent');
echo "</div>";
echo "<br/>";

Answer Source

FIRST in controller you have to echo the message

 $msg = '';
 if($this->email->send()) {
     $msg = 'Email sent successfully'; 
 } else {   
     $msg ='Error in sending'; 
 echo $msg;die;

SECOND in ajax just add the respone to the corresponding div:

  success: function(result) {
           if (result)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download