Jeeva Jeeva - 4 months ago 34
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

COntroller

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

echo json_encode($data);
$this->load->library('email');

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

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

//$this->load->view('adminhp');
} 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) {

event.preventDefault();
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();

jQuery.ajax({
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#result").show();
jQuery("div#rslt").html("Sent Successfully");
console.log("Success");

}
}
});
});
});


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

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)
           {
                console.log(result);
                jQuery("div#result").show();
                jQuery("div#rslt").html(result);

           }
Comments