I’m using ajax to send an email through a contact form in codeigniter. The ajax (jquery) part is:
var dataString = 'nome=' + nome + '&msg=' + msg + '&email=' + email + '&secure=' + secure + '&mailto=' + mailto + '&ci_token=' + $.cookie("ci_csrfprotection_cookie");
$.ajax({
url: '<?php echo site_url();?>/contact/send',
type: 'POST',
data: dataString,
timeout: 1000,
dataType: "json",
success: function(msg){
if(msg.sent){
$('#feedback').html("<?php echo lang('email_sucesso'); ?>").delay(6000).hide('slow');
}
else{
$('#feedback').html("<?php echo lang('email_erro'); ?>").delay(6000).hide('slow');
}
botao.attr('disabled', false);
}
});
And the controller is:
public function send()
{
if ($this->input->post('secure') != 'siteform') {
echo lang('erro_no_js');
}else{
$this->load->library('email');
$nome = $this->input->post('nome');
$email = $this->input->post('email');
$msg = $this->input->post('msg');
$mailto = $this->input->post('mailto');
$secure = $this->input->post('secure');
$config['protocol'] = "smtp";
$config['smtp_host'] = "ssl://smtp.googlemail.com";
$config['smtp_port'] = "465";
$config['smtp_user'] = $this->settings['smtp_email'];
$config['smtp_pass'] = $this->settings['smtp_password'];
$config['charset'] = "utf-8";
$config['mailtype'] = "html";
$config['newline'] = "\r\n";
$this->email->initialize($config);
$this->email->from($email, $nome);
$this->email->to($mailto);
$this->email->subject('Contacto do site');
$this->email->message($msg);
if ($this->email->send()){
echo json_encode(array("sent"=>TRUE));
}else{
echo json_encode(array("sent"=>FALSE));
}
}
}
This actually sends the email correctly but the ajax call gets aborted and I never get a message back.
But if I remove the $this->email->send() bit, I get the response correctly but, of course, the email isn’t sent.
What am I missing here?
Note: I have CSRF enabled and it’s working ok in other ajax calls that query the database.
Try setting async to false like this.
Another way to try would be to use the
completefunction rather than the success function and lease async to true (which is the default). I think the complete function waits without a browser lock, but i’m not 100% certain of this.