mudit mehrotra
mudit mehrotra

Reputation: 71

Unable to get the response in jquery after sending email from codeigniter controller

I am not getting the response after including the send email function to the controller but code sends email perfectly only issue is not getting response. If I remove the code that sends email then in that case response is fine from the controller but when I include the email function I am not getting the response on jquery view code.

I am posting my controller code with the email function code also post my jQuery so that you can review it.

Controller code: /*******Create new customer*******/

public function createcustomer()
    {
        $this->form_validation->set_rules("firstname", "First Name", "required");
        $this->form_validation->set_rules("lastname", "Last Name", "required");
        $this->form_validation->set_rules("email", "Email", "required|is_unique[gab_users.email]|trim|xss_clean");
        $this->form_validation->set_rules('password', 'Password', 'required|min_length[5]|matches[confirmpassword]|md5');
        $this->form_validation->set_rules('confirmpassword', 'Password Confirmation', 'required|min_length[5]');

    if($this->form_validation->run() === FALSE)
    {
        die("fail");
    }
    else
    {
        $activation_code = sha1(uniqid($this->input->post('email'),'true'));
        $data = array("firstname"=>$this->input->post('firstname'), "lastname"=>$this->input->post('lastname'), "email"=>$this->input->post('email'), "password"=>$this->input->post('password'), "ip"=>$this->input->post('ip'), "activation_code"=>$activation_code, "created_on"=>now(), "active"=>1, "group"=>2);
        $verifyCreate = $this->index_model->set_user($data);

        if($verifyCreate === "success")
        {               

                if($this->sendEmail() === 'done')//If I remove this line and write only die('done'); its work perfectly. model is working fine data is saved in the database in both conditions. The big issue is response?
                {die('done');}
        }
        else
        {
            die("invalid");
        }

    }

}
**/******Send Email********/**
public function sendEmail()
{
      $this->load->library('email'); 
      $this->email->set_newline("\r\n");
      $this->email->from('[email protected]', 'Name');
      $this->email->to('*****@gmail.com');
      $this->email->subject(' My mail through codeigniter from localhost '); 
      $this->email->message('Hello World…');
      if (!$this->email->send()) {
        die(show_error($this->email->print_debugger())); 
        }
      else {
        die("done"); //I have also check it by return same thing is happened
      }
}

My Jquery code written in view side:

<script>$().ready(function() {
    $("#regForm").validate({
        rules: 
        {
            firstname: "required",
            lastname: "required",
            email: 
            {
                required: true,
                email: true
            },
            password: 
            {
                required: true,
                minlength: 5
            },
            confirmpassword: 
            {
                required: true,
                minlength: 5,
                equalTo: "#password"
            }
        },
        messages: 
        {
            firstname: "First Name Required",
            lastname: "Last Name required",
            email: "Please enter a valid email address",
            password: 
            {
                required: "Please provide a password",
                minlength: "Your password must be at least 5 characters long"
            },
            confirmpassword: 
            {
                required: "Please provide a password confirmation",
                minlength: "Your password must be at least 5 characters long",
                equalTo: "Please enter the same password as above"
            }
        },
        submitHandler: function(form) 
        {alert('customer register');
          $.ajax({
            type: "POST",
            url: "<?php echo base_url(); ?>createcustomer",
            data: $(form).serialize(),
            timeout: 3000,
            success: function(data) {
            alert(data);
                if(data == 'done')
                {
                    $.blockUI({ css: {
                                border: 'none',
                                padding: '15px',
                                backgroundColor: '#000',
                                '-webkit-border-radius': '10px',
                                '-moz-border-radius': '10px',
                                opacity: .5,
                                color: '#fff'
                            } });

                            setTimeout($.unblockUI, 2000);
                    $('#successreg').show().delay(7000).fadeOut();
                    window.setTimeout(function(){
                        window.location.href = "<?php echo base_url(); ?>customer";
                    }, 7000);

                }
                else if(data == 'invalid')
                {
                   $.blockUI({ css: {
                                border: 'none',
                                padding: '15px',
                                backgroundColor: '#000',
                                '-webkit-border-radius': '10px',
                                '-moz-border-radius': '10px',
                                opacity: .5,
                                color: '#fff'
                            } });

                            setTimeout($.unblockUI, 2000);
                            $('#regerrormsg').show().delay(7000).fadeOut();
                    window.setTimeout(function(){
                        window.location.href = "<?php echo base_url(); ?>customer";
                    }, 7000);
                }
                else
                {
                   $.blockUI({ css: {
                                border: 'none',
                                padding: '15px',
                                backgroundColor: '#000',
                                '-webkit-border-radius': '10px',
                                '-moz-border-radius': '10px',
                                opacity: .5,
                                color: '#fff'
                            } });

                            setTimeout($.unblockUI, 2000);
                    $('#regerrormsg').show().delay(7000).fadeOut();
                    window.setTimeout(function(){
                        window.location.href = "<?php echo base_url(); ?>customer";
                    }, 7000);
                }
            }
          });
          return false;
        }

    });

}); </script>

Please advise why I am not getting response from the controller after using the sendEmail function while the email is send and data is saved to the database but not getting response so I am unable to display the confirmation message to the user.

Upvotes: 0

Views: 164

Answers (1)

Mike Miller
Mike Miller

Reputation: 3129

EDIT: Note the below all that is good stuff as well but your actual issue is how you are returning from your sendMail() function. Die is wrong as it will kill the script dead (clue is in the name) so it wont progress to allow the calling script to respond. Change to:

 ....
 if (!$this->email->send()) {
    die(show_error($this->email->print_debugger())); 
    }
  else {
    return "done"; 
  }

Die is not good practice for a http response as it might be construed as a broken page. Why not return something the jQuery likes eg a json string. For example:

header('Content-Type: application/json');
if($verifyCreate === "success")
    {               

            if($this->sendEmail() === 'done'){
                 echo json_encode(array('status'=>'success'));
                 return;
            }
    }
    else
    {
        echo json_encode(array('status'=>'fail'));
        return;
    }

Then in your jQuery

    //redacted
    success: function(data) {
         if(data.status==='success'){
              //do some success stuff
         }
         else if(data.status==='fail'){
              //do some fail stuff
         }else{
              //do some unexpected stuff
         }
    }

You might also need to set contentType:json in your $.ajax object.

Upvotes: 1

Related Questions