Welcome Guest, Not a member yet? Register   Sign In
Ajax base Form validation?
#1

[eluser]Unknown[/eluser]
Hi i am new to codeigniter , how to validate the form element using ajax.
any body can help me out.
Thanks in advance.
#2

[eluser]Atharva[/eluser]
You can have a look at jquery validation plugin for this located here
#3

[eluser]cideveloper[/eluser]
One thing you should make sure you do is gracefully degrade your form. Make sure it works without JavaScript enabled as well as with. This is just a basic form validation example using CI form validation and Jquery. Take note: I have enclosed the javascript in square brackets cause the forum removes it if you use <>, so you need to replace those.

Controller - welcome.php
Code:
class Welcome extends MY_Controller {

    function __construct()
    {
        //Contructor function
        parent::MY_Controller();
    }

    function index()
    {
        $this->load->library('form_validation');
        $this->form_validation->set_rules('email', 'Email', 'required|xss_clean|valid_email');
        $this->form_validation->set_rules('password', 'Password', 'required|xss_clean|min_length[6]|max_length[18]');
        $this->form_validation->set_rules('confirm_password', 'Password Confirmation', 'required|xss_clean|min_length[6]|max_length[18]|matches[password]');
        $data['title'] = 'get177539';
        if ($this->form_validation->run() == FALSE){
            if(IS_AJAX) {
                $data = array (
                    'status' => false,
                    'msg' => validation_errors()
                );
                echo json_encode($data);
            } else {
                $this->load->view('welcome_form');
            }
        } else {
            $data = array (
                'status' => true,
                'msg' => '<h1>Form Submitted</h1>'
            );
            if(IS_AJAX) {
                echo json_encode($data);
            } else {
                $this->load->view('welcome_formsuccess', $data);
            }
        }
    }

}

Form View - welcome_form.php
Code:
<!DOCTYPE HTML>
&lt;html lang="en"&gt;
&lt;head&gt;
&lt;meta charset="utf-8" /&gt;
&lt;title&gt;CI and JQuery Form Validation&lt;/title&gt;
&lt;link rel="stylesheet" href="style.css" /&gt;
&lt;/head&gt;
&lt;body&gt;
<div>
&lt;form id="val_form" action="&lt;?=site_url('welcome')?&gt;" method="post"&gt;
<p><label for="email">Email:</label>&lt;input type="text" name="email" id="email" value="&lt;?php echo set_value('email'); ?&gt;" /&gt;&lt;/p>
<p><label for="password">Password:</label>&lt;input type="password" name="password" id="password" value="&lt;?php echo set_value('password'); ?&gt;" /&gt;&lt;/p>
<p><label for="confirm_password">Confirm Password:</label>&lt;input type="password" name="confirm_password" id="confirm_password" value="&lt;?php echo set_value('password'); ?&gt;" /&gt;&lt;/p>
<p>&lt;input type="submit" value="Submit" class="button" /&gt;&lt;/p>
&lt;/form&gt;
<p id="val_form_errors">
&lt;?php echo validation_errors(); ?&gt;
</p>
</div>
[script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"][/script]
[script type="text/javascript" src="&lt;?=base_url()?&gt;assets/js/site.js"][/script]
&lt;/body&gt;
&lt;/html&gt;

Success View - welcome_formsuccess.php
Code:
<!DOCTYPE HTML>
&lt;html lang="en"&gt;
&lt;head&gt;
&lt;meta charset="utf-8" /&gt;
&lt;title&gt;CI and JQuery Form Validation&lt;/title&gt;
&lt;link rel="stylesheet" href="style.css" /&gt;
&lt;/head&gt;
&lt;body&gt;
<div>
&lt;?=$msg;?&gt;
</div>
[script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"][/script]
[script type="text/javascript" src="&lt;?=base_url()?&gt;assets/js/site.js"][/script]
&lt;/body&gt;
&lt;/html&gt;


JQuery - site.js
Code:
$(function(){

    $('#val_form').submit(function(e){
        $('#val_form_errors').hide();
        e.preventDefault();
        $.post($(this).attr('action'),$(this).serialize(),function(data){
            //console.log(data);
            if (data.status){
                $('#val_form_errors').html(data.msg).fadeIn('slow').css({'color':'green', 'border':'1px solid green', 'padding':'20px', 'display': 'inline-block'});
            } else {
                $('#val_form_errors').html(data.msg).fadeIn('slow').css({'color':'red', 'border':'1px solid #FF3333', 'padding':'20px', 'display': 'inline-block'});
            }

        }, 'json');
    });

});
#4

[eluser]boony[/eluser]
Hi,

Excellent post, this basic setup for form validation is valuable info for any ci newbie looking to integrate some ajax functionality.

However, again for any newbie it may help to explain the IS_AJAX constant, as this is not part of the core constants set up.

The following sript should be placed at the bottom of the application/config/constants.php file.
Code:
// Define Ajax Request
define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');


Hope this helps.
#5

[eluser]cideveloper[/eluser]
@boony - good catch there. Im so used to adding that, when I initially set-up CI, that I forget its not part of the core. CI2 has a built in object in the input class i think.
#6

[eluser]Unknown[/eluser]
Thanks! for helping me. its really nice. and helpfull for me.
#7

[eluser]Unknown[/eluser]
I am new to CI and i don't know where should I place site.js?
#8

[eluser]boony[/eluser]
[quote author="elinad" date="1296136950"]I am new to CI and i don't know where should I place site.js?[/quote]

Hi,

You should look at the intro to ci tutorials first. But the basic structure would be to create a folder in the root folder (call it js or assets or whatever) and put the site.js in there, as the following

ci
-application
-system
-js
-site.js

You can then refer to the site.js in the head section like this


Code:
[script type="text/javascript" src="&lt;?=base_url();?&gt;/js/site.js">&lt;/script]


essentially, all the assets files like css and images folders should be placed in the root directory and referenced as above.

Hope this helps Smile
#9

[eluser]BrianJM[/eluser]
boony, I use a slightly different structure (there's absolutely nothing wrong with what you do:
Quote:* application
* public
&nbsp;&nbsp;&nbsp;* js
&nbsp;&nbsp;&nbsp;* css
&nbsp;&nbsp;&nbsp;* img
* system

My .htaccess is as follows:
Code:
RewriteEngine on

#Allow these
RewriteCond $1 !^(index\.php|images|robots\.txt|public)
RewriteRule ^(.*)$ /index.php/$1 [L]

My application/views/header.php contains the following:
Code:
[script type="text/javascript" src="&lt;?=base_url();?&gt;public/js/{FILE_NAME}.js">&lt;/script]
#10

[eluser]Unknown[/eluser]
[quote author="cideveloper" date="1295137612"]One thing you should make sure you do is gracefully degrade your form. Make sure it works without JavaScript enabled as well as with. This is just a basic form validation example using CI form validation and Jquery. Take note: I have enclosed the javascript in square brackets cause the forum removes it if you use <>, so you need to replace those.

Controller - welcome.php
Code:
class Welcome extends MY_Controller {

    function __construct()
    {
        //Contructor function
        parent::MY_Controller();
    }

    function index()
    {
        $this->load->library('form_validation');
        $this->form_validation->set_rules('email', 'Email', 'required|xss_clean|valid_email');
        $this->form_validation->set_rules('password', 'Password', 'required|xss_clean|min_length[6]|max_length[18]');
        $this->form_validation->set_rules('confirm_password', 'Password Confirmation', 'required|xss_clean|min_length[6]|max_length[18]|matches[password]');
        $data['title'] = 'get177539';
        if ($this->form_validation->run() == FALSE){
            if(IS_AJAX) {
                $data = array (
                    'status' => false,
                    'msg' => validation_errors()
                );
                echo json_encode($data);
            } else {
                $this->load->view('welcome_form');
            }
        } else {
            $data = array (
                'status' => true,
                'msg' => '<h1>Form Submitted</h1>'
            );
            if(IS_AJAX) {
                echo json_encode($data);
            } else {
                $this->load->view('welcome_formsuccess', $data);
            }
        }
    }

}

Form View - welcome_form.php
Code:
<!DOCTYPE HTML>
&lt;html lang="en"&gt;
&lt;head&gt;
&lt;meta charset="utf-8" /&gt;
&lt;title&gt;CI and JQuery Form Validation&lt;/title&gt;
&lt;link rel="stylesheet" href="style.css" /&gt;
&lt;/head&gt;
&lt;body&gt;
<div>
&lt;form id="val_form" action="&lt;?=site_url('welcome')?&gt;" method="post"&gt;
<p><label for="email">Email:</label>&lt;input type="text" name="email" id="email" value="&lt;?php echo set_value('email'); ?&gt;" /&gt;&lt;/p>
<p><label for="password">Password:</label>&lt;input type="password" name="password" id="password" value="&lt;?php echo set_value('password'); ?&gt;" /&gt;&lt;/p>
<p><label for="confirm_password">Confirm Password:</label>&lt;input type="password" name="confirm_password" id="confirm_password" value="&lt;?php echo set_value('password'); ?&gt;" /&gt;&lt;/p>
<p>&lt;input type="submit" value="Submit" class="button" /&gt;&lt;/p>
&lt;/form&gt;
<p id="val_form_errors">
&lt;?php echo validation_errors(); ?&gt;
</p>
</div>
[script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"][/script]
[script type="text/javascript" src="&lt;?=base_url()?&gt;assets/js/site.js"][/script]
&lt;/body&gt;
&lt;/html&gt;

Success View - welcome_formsuccess.php
Code:
<!DOCTYPE HTML>
&lt;html lang="en"&gt;
&lt;head&gt;
&lt;meta charset="utf-8" /&gt;
&lt;title&gt;CI and JQuery Form Validation&lt;/title&gt;
&lt;link rel="stylesheet" href="style.css" /&gt;
&lt;/head&gt;
&lt;body&gt;
<div>
&lt;?=$msg;?&gt;
</div>
[script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"][/script]
[script type="text/javascript" src="&lt;?=base_url()?&gt;assets/js/site.js"][/script]
&lt;/body&gt;
&lt;/html&gt;


JQuery - site.js
Code:
$(function(){

    $('#val_form').submit(function(e){
        $('#val_form_errors').hide();
        e.preventDefault();
        $.post($(this).attr('action'),$(this).serialize(),function(data){
            //console.log(data);
            if (data.status){
                $('#val_form_errors').html(data.msg).fadeIn('slow').css({'color':'green', 'border':'1px solid green', 'padding':'20px', 'display': 'inline-block'});
            } else {
                $('#val_form_errors').html(data.msg).fadeIn('slow').css({'color':'red', 'border':'1px solid #FF3333', 'padding':'20px', 'display': 'inline-block'});
            }

        }, 'json');
    });

});
[/quote]
Where is the style.css that you linked to or where we supposed to make it ourselves ?




Theme © iAndrew 2016 - Forum software by © MyBB