CodeIgniter Forums
Codeigniter AJAX validation email form - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forum-20.html)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forum-23.html)
+--- Thread: Codeigniter AJAX validation email form (/thread-55891.html)



Codeigniter AJAX validation email form - El Forum - 11-15-2012

[eluser]balboa_1990[/eluser]
After completing a php form using CI and the email class, i am able to receive html emails with the users data included-great. Now, as well as the CI validation, i would like to include client side validation (AJAX) with a nice fadeIn or fadeOut effect and still have CI validation running incase javascript is turned off. The code included here is what i have achieved so far from various sources and i know this is not complete but not even sure if im on the right tracks? So far with what i have the form still works fine and i assume its still running the CI validation script and there are no effects taken place. I would be gratfeul if someone could guide me to where i have went wrong so far and if possible what next steps to take? Here is the code to support my question:

NOTE: This is not my whole script, i've put in the relevant code and brackets what would be supporting it


VIEW
Code:
<div id="contact">
&lt;?php

$this->load->helper('form');

echo form_open('contact/send_email');

echo $success;

// empty div for error messages (php)
if(validation_errors() != ""){
    echo '<h3>Please correct the following errors:</h3>';
    echo '<div id="errors">';
    echo validation_errors();
    echo '</div>';
}


echo form_label('Email: ', 'email');
    $data = array (
        'name' => 'email',
        'id' => 'email',
        'value' =>set_value('email')
    );
echo form_input($data);

[I also have two more arrays for message and name, set out the same as email]


echo form_submit('submit', 'Send');

echo form_close();
?&gt;



AJAX

Code:
$(function() {
    $('form').click(function() {

        // get the form values
        var form_data = {
            name: $('name').val(),
            email: $('email').val(),
            message: $('message').val()
        };

        // send the form data to the controller
        $.ajax({
            url: "&lt;?php echo site_url('contact/send_email'); ?&gt;",
            type: "post",
            data: form_data,
            success: function(msg)
            {
            if(msg.validate)
                    {
                    $('form').prepend('<p>Message sent!</p>');
                    $('p').delay(3000).fadeOut(500);
                    }
                    else
                     $('form').prepend('<div id="errors">Message Error</div>');
                     $('p').delay(3000).fadeOut(500);
                }
            });
            return false;  
        });
    });
    [removed]


CONTROLLER
Code:
function __construct() {
    parent::__construct();
}

public function index()
{  
    $data['success'] = '';
    $data['page_title'] = 'Contact';
    $data['content'] = 'contact';
    $this->load->view('template', $data);
   }

public function send_email (){
    $this->load->library('form_validation');

    [SET RULES ARE LOCATED HERE]

    [ERROR DELIMITERS HERE]

    if ($this->form_validation->run() === FALSE) {
        $data['success'] = '';
        $data['page_title'] = 'Contact';
        $data['content'] = 'contact';
        $this->load->view('template', $data);  

    }else{
        $data['success'] = 'The email has successfully been sent';
        $data['name'] = $this->input->post('name');
        $data['email'] = $this->input->post('email');
        $data['message'] = $this->input->post('message');

        $html_email = $this->load->view('html_email', $data, true);

        //load the email class
        $this->load->library('email');

        $this->email->from(set_value('email'), set_value('name'));
        $this->email->to('-----EMAIL----');
        $this->email->subject('Message from Website');
        $this->email->message($html_email);

        $this->email->send();

        $data['page_title'] = 'Contact';
        $data['content'] = 'contact';  
        $this->load->view('template', $data);

        return null;
    }
}
}



Codeigniter AJAX validation email form - El Forum - 11-15-2012

[eluser]balboa_1990[/eluser]
I forgot to say, i've also tested this by putting an alert in the AJAX and still nothing. I know i am missing something in my controller though i think?


Codeigniter AJAX validation email form - El Forum - 11-15-2012

[eluser]LuckyFella73[/eluser]
Regarding your js success function:
You have to echo out soemthing to return information
to your ja function. Use "echo" or "die()". I use
to "die()" a json encoded result, that way you can
send the matching message to your js function having
it more flexible.

Code:
// Controller:

// for example
$result = array(
'msg' => 'You mail was send',
'validation_flag'=> 0, // you can define levels for each possible situation (success, error, info about missing input ...
);

// built this array depending on your validation and what kind of feedback you want to give to the user

die(json_encode($result));


// in your js (success function) switch through 'validation_flag' and
do the needed actions like show message or whatever

Btw.: it can't be bad to use the csrf protection


Codeigniter AJAX validation email form - El Forum - 11-15-2012

[eluser]balboa_1990[/eluser]
Thanks for your comment but still no luck with it. Not sure if anyone can guide me to a tutorial or another method in which i can complete this? Thanks.


Codeigniter AJAX validation email form - El Forum - 11-16-2012

[eluser]LuckyFella73[/eluser]
Your js and controller code basically should look like this
(if I get you right on what you are going to achieve):
Code:
// your js
$(function() {
$('#form').submit(function (e) {
e.preventDefault();

// get the form values
var form_data = {
  name: $('name').val(),
  email: $('email').val(),
  message: $('message').val()
};

$.ajax({
  url   : "&lt;?php echo base_url('contact/send_email'); ?&gt;",
  data  : form_data,
  type  : "post",
  dataType :"JSON",
  success: function(result) {
   if(result.validate == 1) {
    $('form').prepend('<p>Message sent!</p>');
    $('p').delay(3000).fadeOut(500);
   }
   else {
    $('form').prepend('<div id="errors">Message Error</div>');
    $('p').delay(3000).fadeOut(500);
   }
  }
})
});

}); // closing tag - document.ready


// Your Controller
public function send_email ()
{
// Don't load views here for you are only going to return a json result
// to your ajax function here

$result = array();
  
    $this->load->library('form_validation');


// [SET RULES ARE LOCATED HERE]
    // [ERROR DELIMITERS HERE]

    if ($this->form_validation->run() === FALSE)
{
  // Code here
  $result['validate'] = 0; // failed
}
else
{
       // Code here
    // email stuff
    
    $result['validate'] = 1; // succeeded
    }

die(json_encode($result));
}

Be sure your selector ( submit action ) matches


Codeigniter AJAX validation email form - El Forum - 11-16-2012

[eluser]balboa_1990[/eluser]
LuckyFella73- Thank you, i knew it was something to do in the controller, I am nearly there and with your snippets the following occurs:

Leave the Form blank: Error message appears and fades-fab
Fill in the form correctly: Error message appears however the email appears in my inbox (so it knows its successful).

I am not sure if I've positioned the result array in my controller or if the "if else" statement i have them mixed up? Ive added new div id the selectors so i can see if there is any change but it looks like it repeats the error selector. Here is my code below for the overall structure from your advice:

Note: not sure if i need to add dataType:html as I'm sending a html email (html view is loaded in the controller).

Thanks!

VIEW
Code:
<h1>Contact</h1>
<div id="contact">
&lt;?php
//This is loaded in the view as it wont be used in the other pages
$this->load->helper('form');

echo form_open('contact/send_);

//success message if passed validation checks
echo '<div id="success">';
echo $success;
echo '</div>';

// empty div for error messages (ajax)
echo '<div id="errors">';

// empty div for error messages (php)
if(validation_errors() != ""){
    echo '<h3>Please correct the following errors:</h3>';
    echo validation_errors();
}

echo '</div>';

echo form_label('Name: ', ');
    $data = array (
        ' => ',
        'id' => ',
        'value' => set_value(')
    );
echo form_input($data);


echo form_label('Email: ', ');
    $data = array (
        ' => ',
        'id' => ',
        'value' =>set_value(')
    );
echo form_input($data);


echo form_label('Message: ', ');
    $data = array (
        ' => ',
        'id' => ',
        'value' =>set_value(')
    );
echo form_textarea($data);
?&gt;

<br />

&lt;?php
echo form_submit('submit', 'Send');

echo form_close();
?&gt;

[removed]
$(function() {
$('form').submit(function(e){
  e.preventDefault();

  // get the form values
  var form_data = {
   name: $('#name').val(),
   email: $('#email').val(),
   message: $('#message').val()
  };

  $.ajax({
   url:"&lt;?php echo base_url('contact/send_); ?&gt;",
    data:form_data,
    type:"post",
    dataType :"JSON",
    success: function(result) {
    
  if(result.validate == 1) {
   $('form').prepend('<div id="success">Message Successful</div>');
   $('#success').fadeOut(1000);
  }else{
   $('form').prepend('<div id="errors">Message Error</div>');
   $('#errors').fadeOut(1000);
      }
    }
  })
});
}); // closing tag - document.ready
[removed]

</div>

CONTROLLER
Code:
&lt;?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Contact extends CI_Controller {

function __construct() {
  parent::__construct();
}

public function index()
{
  $data['success'] = '';
  $data['page_title'] = 'Contact';
  $data['content'] = 'contact';
  $this->load->view('template', $data);
  }
  
   public function send_email (){
  
  $result = array();
  
  $this->load->library(');
  
  $this->form_validation->set_rules(','Name','trim|required|htmlspecialchars|alpha|max_length[30]|xss_clean');
   $this->form_validation->set_rules(','Email Address','trim|valid_email|required|htmlspecialchars|max_length[75]|xss_clean');
  $this->form_validation->set_rules(','Message','trim|required|htmlspecialchars|xss_clean');
  
  $this->form_validation->set_error_delimiters('<div id="errors">&bull;&nbsp;','</div>');
  
  if ($this->form_validation->run() == FALSE) {
  
   $result['validate'] = 0; // failed
  
   $data['success'] = '';
   $data['page_title'] = 'Contact';
   $data['content'] = 'contact';
   $this->load->view('template', $data);


  }else{
   $data['success'] = 'The email has successfully been sent';
   $data['] = $this->input->post(');
   $data['] = $this->input->post(');
   $data['] = $this->input->post(');
  
   $html_email = $this->load->view('html_email', $data, true);

   //load the email class
   $this->load->library(');
  
   $this->email->from(set_value('), set_value('));
   $this->email->to('email-address-removed');
   $this->email->subject('Message from Website');
   $this->email->message($html_email);
  
   $this->email->send();
  
   $data['page_title'] = 'Contact';
   $data['content'] = 'contact';
   $this->load->view('template', $data);
  
   $result['validate'] = 1; // succeeded
  
        }
        die(json_encode($result));
   }
}



Codeigniter AJAX validation email form - El Forum - 11-16-2012

[eluser]balboa_1990[/eluser]
I think its actually something in the set_error_delimiters in the controller as when i remove that line, and type in the code, the error code does not repeat when the form is filled in and is sent BUT still no success message! Checking in firebug the error message is still repeated though, oh dear!


Codeigniter AJAX validation email form - El Forum - 11-16-2012

[eluser]LuckyFella73[/eluser]

Did you do a "replace taks" with your editor?
Your controller code is full of (') and [']

Did I get you right that you want to submit the form
via ajax? Your code is somehow mixed like you want
to submit the form the "normal" way (echoing out a
success message) and via ajax the same time. You can
only go one way.


Codeigniter AJAX validation email form - El Forum - 11-16-2012

[eluser]balboa_1990[/eluser]
The aim of the contact form is the user fills it in and when successful, it will show a success message to them and the email will be sent (html version which works) and when they have left blank fields or non alpha characters ect an error message appears. I wanted to use a AJAX form so it does not refresh the page and have fade in/out effects on the messages and if the user has Javascript turned off the codeigniter php is still active - have i went around this the wrong way?


Codeigniter AJAX validation email form - El Forum - 11-16-2012

[eluser]LuckyFella73[/eluser]
You have to decide if you want to submit the form via ajax
or just validate. If you only want to validate the form via
ajax the js-success message makes no sense anymore.

What you need is:
- a controller method only for validating the form input
-> this method only validates! no email is send here, no views are loaded

- a controller having all the validation and email functions and views
-> here you set a success message send to the view in case the validation
went through.

- a js function that calls the ajax validation method
-> this function calls the validation method of the ajax controller and
tells your form if the validation went through or not. If not you
display the error message. If the form input was valid the form is
send to the controller (page request) having the validation AND mail function and views.