{"id":33,"date":"2017-09-01T17:18:17","date_gmt":"2017-09-01T17:18:17","guid":{"rendered":"https:\/\/codingfix.com\/?p=33"},"modified":"2017-12-11T15:21:33","modified_gmt":"2017-12-11T15:21:33","slug":"sending-email-using-ajax-codeigniter","status":"publish","type":"post","link":"https:\/\/codingfix.com\/sending-email-using-ajax-codeigniter\/","title":{"rendered":"Sending an email using Ajax from CodeIgniter"},"content":{"rendered":"<p>In this small article I&#8217;ll show use how to send an email from your CodeIgniter website without submitting a form and reloading the page, but using Ajax to call a controller method and get instantly the response in your page.<\/p>\n<h2 class=\"align-justify\">Setting up CodeIgniter part.<\/h2>\n<p>If you are reading this, I suppose you already know what CodeIgniter is and how it works (otherwise you can start to learn <a href=\"https:\/\/www.codeigniter.com\/userguide3\/\" target=\"_blank\" rel=\"noopener\">here<\/a>). I assume also you have your own domain and a CodeIgniter application already installed. In this small tutorial we&#8217;re going to use a bunch of files:<\/p>\n<ul>\n<li>the controller Main<\/li>\n<li>the views start_view and contact_view<\/li>\n<li>CodeIgniter configuration files config.php and route.php<\/li>\n<\/ul>\n<h2>Configuration files<\/h2>\n<p>First be sure that in your config\/config.php file the variable <strong>$config[&#8216;base_url&#8217;]<\/strong> be set correctly to your domain. If your domain is <em>www.mydomain.com<\/em> then in the config file we&#8217;ll have:<\/p>\n<pre class=\"lang:default decode:true\">$config['base_url'] = 'http:\/\/www.mydomain.com\/';<\/pre>\n<p>As you know, CodeIgniter allows you to use a really comfortable method to write your links: base_url() method:<\/p>\n<pre class=\"lang:default decode:true\">&lt;a href=\"&lt;?php echo base_url('contacts') ?&gt;\"&gt;Contacts&lt;\/a&gt;<\/pre>\n<p>Now we can open <em>application\/config\/route.php<\/em> file to do some change. I&#8217;ll assume that our controller will be the default controller in our app, so in route.php file we&#8217;ll have to setup correctly the value of the variable <strong>$route[&#8216;default_controller&#8217;]<\/strong>. In addition we have to add a line to manage our contact page link:<\/p>\n<pre class=\"lang:default decode:true\">$route['default_controller'] = 'Main';\r\n$route['404_override'] = '';\r\n$route['contacts'] = 'Main\/contacts';<\/pre>\n<h2>The controller<\/h2>\n<p>In our controller we have only index method which load the start_view:<\/p>\n<pre class=\"lang:default decode:true\">public function contacts() { \r\n    $this-&gt;load-&gt;view( 'start_view' );\r\n}<\/pre>\n<p>In the start_view we&#8217;ll just display a link to our contact form. I confess you&#8217;ll find very poor the style of these pages, but we have to focus on underlying code, isn&#8217;t it?<\/p>\n<p>In Main controller we have to manage also the loading of the contact view and the method which actually sends our emails. The complete controller scripts looks like this one:<\/p>\n<pre class=\"lang:default decode:true \">&lt;?php\r\n\r\nif (!defined('BASEPATH')) {\r\n\texit('No direct script access allowed');\r\n}\r\n\r\nclass Main extends CI_Controller {\r\n\r\n    public function index()\r\n    {\r\n\t$this-&gt;load-&gt;view( 'start_view' );\r\n    }\r\n\r\n    public function contacts()\r\n    {\r\n\t$this-&gt;load-&gt;view( 'contacts_view' );\r\n    }\r\n\r\n    public function sendemail()\r\n    {\r\n        $name = $_POST['name'];\r\n        $email = $_POST['email'];\r\n        $message = $_POST['message'];\r\n        $to = 'mailbox@mydomain.com';\r\n        $subject = 'New message from your website';\r\n        $headers = \"From: \" . strip_tags($email) . \"\\r\\n\";\r\n        $headers .= \"Reply-To: \". strip_tags($email) . \"\\r\\n\";\r\n        $headers .= \"MIME-Version: 1.0\\r\\n\";\r\n        $headers .= \"Content-Type: text\/html; charset=ISO-8859-1\\r\\n\";\r\n        if (mail($to, $subject, $message, $headers))\r\n        {\r\n             echo 'Your message has been correctly sent. Thank you for contacting us: we'll reply as soon as possible&lt;br&gt;&lt;h4 style=\"text-align: right;\"&gt;Lo Our staff&lt;\/h4&gt;';\r\n        }\r\n        else\r\n        {\r\n            echo 'Ooops, I'm sorry but something went wrong sending your message. Please contact us at this address: '.safe_mailto( support@yourdomain.com );\r\n        }\r\n    }\r\n}<\/pre>\n<p>As you can see, there&#8217;s nothing special: the method <em>contacts()<\/em> loads the contact view which displays a form to sen emails: when the user cliks the Send button the method <em>sendemail()<\/em> actually sends an image and echoes a message accordingly. This method is not reached by CodeIgniter through the routing system after a form submission: it&#8217;s instead called by jQuery through an Ajax call: this is the reason why this method doesn&#8217;t load any view: the view remain the current one, that is <em>contact_view.<\/em><\/p>\n<h2>The views<\/h2>\n<p>This one is the interesting part, but let me quickly introduce our views. The first is <em>start_view<\/em>, the one that is loaded when we enter the site visiting thhe url <em>www.mydomain.com<\/em><\/p>\n<p>The <em>start_view:<\/em><\/p>\n<pre class=\"lang:default decode:true\">&lt;?php\r\ndefined('BASEPATH') OR exit('No direct script access allowed');\r\n?&gt;\r\n&lt;!DOCTYPE html&gt;\r\n&lt;html lang=\"en\"&gt;\r\n    &lt;head&gt;\r\n        &lt;meta charset=\"utf-8\"&gt;\r\n        &lt;title&gt;Send email Start page&lt;\/title&gt;\r\n    &lt;\/head&gt;\r\n    &lt;body&gt;\r\n        &lt;h1&gt;The start view&lt;\/h1&gt;\r\n        &lt;p&gt;If you don't like this page you can notify me using our &lt;a href=\"&lt;?php echo base_url('contacts'); ?&gt;\"&gt;contacts&lt;\/a&gt; page.&lt;\/p&gt;\r\n    &lt;\/body&gt;\r\n&lt;\/html&gt;<\/pre>\n<p>I suspect we&#8217;re going to get a lot of emails&#8230;<\/p>\n<p>The <em>contacts_view<\/em>:<\/p>\n<pre class=\"lang:default decode:true\">&lt;?php\r\ndefined('BASEPATH') OR exit('No direct script access allowed');\r\n?&gt;\r\n&lt;!DOCTYPE html&gt;\r\n&lt;html lang=\"en\"&gt;\r\n    &lt;head&gt;\r\n        &lt;meta charset=\"utf-8\"&gt;\r\n        &lt;title&gt;Send email Start page&lt;\/title&gt;\r\n    &lt;\/head&gt;\r\n    &lt;body&gt;\r\n        &lt;h1&gt;The contact view&lt;\/h1&gt;\r\n        &lt;p&gt;Use the form to send us an email:&lt;\/p&gt;\r\n        &lt;div id=\"response\"&gt;&lt;\/div&gt;\r\n        &lt;form&gt;\r\n            &lt;label for=\"email\"&gt;Email&lt;\/label&gt;\r\n            &lt;input id=\"email\" type=\"text\" placeholder=\"Email\" \/&gt;\r\n            &lt;br&gt;\r\n            &lt;label for=\"name\"&gt;Nome&lt;\/label&gt;\r\n            &lt;input id=\"name\" type=\"text\" placeholder=\"Name\" \/&gt;\r\n            &lt;br&gt;\r\n            &lt;textarea id=\"message\" placeholder=\"Your message here...\"&gt;&lt;\/textarea&gt;\r\n            &lt;br&gt;\r\n            &lt;button id=\"send\"&gt; Send &lt;\/button&gt;\r\n        &lt;\/form&gt;\r\n    &lt;\/body&gt;\r\n&lt;\/html&gt;<\/pre>\n<p>Notice the div with id set to &#8220;response&#8221; where the message returned by the controller will be displayed.<\/p>\n<p>And, yes, the form is horrible, I know&#8230;<\/p>\n<h2>And now let&#8217;s send an email with Ajax&#8230;<\/h2>\n<p>We&#8217;re finally ready to implement our Ajax code to send email from our CodeIgniter website.<\/p>\n<p>Stay on <em>contacts_view<\/em>: here we&#8217;re going to add our javascript code. First, we include jQuery:<\/p>\n<pre class=\"lang:default decode:true \">&lt;script src=\"https:\/\/ajax.googleapis.com\/ajax\/libs\/jquery\/1.11.1\/jquery.min.js\"&gt;&lt;\/script&gt;<\/pre>\n<p>Secondly, we must to let know jQuery something about our base url, so we&#8217;ll create a variable called <em>baseUrl<\/em> to use in opur script:<\/p>\n<pre class=\"lang:default decode:true \">&lt;script type=\"text\/javascript\"&gt; \r\n    var baseUrl = \"&lt;?php print base_url(); ?&gt;\";\r\n&lt;\/script&gt;<\/pre>\n<p>And finally we can go with tha actual Ajax call:<\/p>\n<pre class=\"lang:default decode:true \">$( document ).on( 'click', '#send', function ( e ) {\r\n    e.preventDefault();\r\n    \/\/hide response if it's visible\r\n    $( '#response' ).hide();\r\n    \/\/we grab all fields values to create our email\r\n    var name = $( '#name' ).val();\r\n    var email = $( '#email' ).val();\r\n    var message = $( '#message' ).val();\r\n    if ( name === '' || email === '' || message === '' )\r\n    {\r\n        \/\/all fields are rquired so if one of them is empty the function returns\r\n        return;\r\n    }\r\n    \/\/if it's all right we proceed\r\n    $.ajax( {\r\n        type: 'post',\r\n        \/\/our baseurl variable in action will call the sendemail() method in our default controller\r\n        url: baseurl + 'sendemail',\r\n        data: { name: name, email: email, message: message },\r\n        success: function ( result )\r\n        {\r\n            \/\/Ajax call success and we can show the value returned by our controller function\r\n            $( '#response' ).html( result ).fadeIn( 'slow' ).delay( 3000 ).fadeOut( 'slow' );\r\n            $( '#name' ).val( '' );\r\n            $( '#email' ).val( '' );\r\n            $( '#message' ).val( '' );\r\n        },\r\n        error: function ( result )\r\n        {\r\n            \/\/Ajax call failed, so we inform the user something went wrong\r\n            $( '#response' ).html( 'Server unavailable now: please, retry later.' ).fadeIn( 'slow' ).delay( 3000 ).fadeOut( 'slow' );\r\n            $( '#name' ).val( '' );\r\n            $( '#email' ).val( '' );\r\n            $( '#message' ).val( '' );\r\n        }\r\n    } );\r\n} );<\/pre>\n<p>That&#8217;s all: it takes longer to say than to do.<\/p>\n<p>Hope you&#8217;ll find useful this article and feel free to leave comments, criticism or everything you want to say&#8230; almost everything \ud83d\ude09<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this small article I&#8217;ll show use how to send an email from your CodeIgniter website without submitting a form and reloading the page, but using Ajax to call a controller method and get instantly the response in your page. Setting up CodeIgniter part. If you are reading this, I suppose you already know what [&hellip;]<\/p>\n","protected":false},"author":3,"featured_media":297,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_gspb_post_css":"","footnotes":""},"categories":[34],"tags":[10,8,11,9,12],"post_folder":[142],"class_list":["post-33","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-other-stuff","tag-ajax","tag-codeigniter","tag-email","tag-jquery","tag-send"],"_links":{"self":[{"href":"https:\/\/codingfix.com\/wp-json\/wp\/v2\/posts\/33","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codingfix.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codingfix.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codingfix.com\/wp-json\/wp\/v2\/users\/3"}],"replies":[{"embeddable":true,"href":"https:\/\/codingfix.com\/wp-json\/wp\/v2\/comments?post=33"}],"version-history":[{"count":0,"href":"https:\/\/codingfix.com\/wp-json\/wp\/v2\/posts\/33\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codingfix.com\/wp-json\/wp\/v2\/media\/297"}],"wp:attachment":[{"href":"https:\/\/codingfix.com\/wp-json\/wp\/v2\/media?parent=33"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codingfix.com\/wp-json\/wp\/v2\/categories?post=33"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codingfix.com\/wp-json\/wp\/v2\/tags?post=33"},{"taxonomy":"post_folder","embeddable":true,"href":"https:\/\/codingfix.com\/wp-json\/wp\/v2\/post_folder?post=33"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}