Shimsham84
Shimsham84

Reputation: 327

Codeigniter AJAX email validation

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 in case 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 I'm on the right track? So far with what I have the form still works fine and I assume it's 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:

VIEW

<div id="contact">
<?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_email');

//success message if passed validation checks
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('Name: ', 'name');
    $data = array (
        'name' => 'name',
        'id' => 'name',
        'value' => set_value('name')
    );
echo form_input($data);


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


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

<br />

<?php
echo form_submit('submit', 'Send');

echo form_close();
?>

-----------AJAX-------------------

$(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: "<?php echo site_url('contact/send_email'); ?>",
            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);
                }
            });
            // prevents from refreshing the page
            return false;   
        });
    });
    </script>

CONTROLLER

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 (){
    $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;
    }
}

}

Upvotes: 0

Views: 2009

Answers (1)

Seto
Seto

Reputation: 1646

Let me try to post my first answer in this community:
1. This is jQuery file, so you should use .submit() method for handling form submit

  $('form').submit(function() { 

but if you want to use click, you should bind it with 'submit' button

  $('input[type="submit"]').click(function() {

2. Instead of gather all you form data in array, you can use .serialize() method

 data: $('form').serialize(),

3. In you controller, why you load view? it's Ajax call, so the common method is return JSON response depend on your result:

 if ($this->form_validation->run() === TRUE) {
    $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();

    $response->validate = true;

    echo json_encode($response);
}

In this situation, I eliminate the FALSE because you already check your result on callback function:

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);
            }
        });

Although this is 2012 question, hope this help for people who stumble upon to this question.

Upvotes: 1

Related Questions