Sie sind auf Seite 1von 7

10/2/2014 Sending forms with AJAX in CodeIgniter - PHP's Blog

http://phpsblog.agustinvillalba.com/sending-forms-ajax-codeigniter/ 1/7
PHP's Blog
PHP and web things for beginners and not so beginners. Here we talk about many web technologies such as php, CodeIgniter,
JavaScript and more.
Ads by Info Ad Options
Home AJAX Sending forms with AJAX in CodeIgniter
Sending forms with
AJAX in CodeIgniter
Posted on November 24, 2013 by Agustin Villalba No Comments
Today we are going to explain how we can send a form via AJAX using
jQuery in CodeIgniter, so we avoid to reload the whole page, giving the
appearance of desktop application to our web application, being able
to perform certain actions without reloading the entire page view.
Creating the form
First, we need to create our form. In this case we will create a generic
form, where we will add different types of fields to make the example
as complete as possible, but functionally not very helpful, mainly for
teaching purposes So in our view file in CodeIgniter we add the
following code:
search here
Go
Tags
ajax APC bug bug-fix
Carabiner cms
CodeIgniter
configuration CSS database
development
drupal email exporting Flash
fork HMVC ImageFlow
inheritance
JavaScript
jQuery JSON library
modules MySQL nusoap
Ads by Info Ad Options
Home
10/2/2014 Sending forms with AJAX in CodeIgniter - PHP's Blog
http://phpsblog.agustinvillalba.com/sending-forms-ajax-codeigniter/ 2/7
$attr = 'id="my_form"'; //The form will have the id
'my_form'
echo form_open('my_controller/process_form',$attr);
//Create a text field
echo form_label('Field1: ','field1');
$data = array(
'name' => 'field1',
'id' => 'field1',
'value' => ''
);
echo form_input($data);
//Create some checkboxes
$data = array(
'name' => 'field2',
'id' => 'field2',
'value' => '2',
'checked' => false
);
echo form_checkbox($data);
$data = array(
'name' => 'field3',
'id' => 'field3',
'value' => '3',
'checked' => false
);
echo form_checkbox($data);
//Create some radio
$data = array(
'name' => 'radio',
'id' => 'radio1',
'value' => 'radio1',
'checked' => false
);
echo form_radio($data);
$data = array(
'name' => 'radio',
'id' => 'radio2',
'value' => 'radio2',
'checked' => false
);
echo form_radio($data);
//And a textarea
echo form_label('Textarea: ','textarea');
$data = array(
'name' => 'textarea',
'id' => 'textarea',
'value' => '',
parallelize pcntl PHP
phpmailer phpMyAdmin plug-in
programming
progress bar scrollTo server
SMTP SOAP SWFUpload
thread trigger upload files url utf-8
Info
Author: Agustn Villalba
www.agustinvillalba.com
PHP's Blog en espaol
Subscribe via
Email
Enter your email address
to subscribe to this blog
and receive notifications of
new posts by email.
Email Address
Subscribe
RSS Feed
RSS - Posts
RSS - Comments
10/2/2014 Sending forms with AJAX in CodeIgniter - PHP's Blog
http://phpsblog.agustinvillalba.com/sending-forms-ajax-codeigniter/ 3/7
'rows' => '2',
'cols' => '50' );
echo form_textarea($data);
echo form_close();
The controller
This is where comes the most important and, for me, also the most
interesting part of the whole process. In our controller we will identify
wether the form was sent by AJAX or by the traditional way (reloading
page). So that, we will be able to load some views or anothers without
having two functions in our controller for the same task. The important
thing is to examine the PHP global variable $_SERVER with an item
called HTTP_X_REQUESTED_WITH, which indicates whether the
request was made via AJAX or using a standard HTTP request. So
that, our controller code would be:
<?php
//Store into the constant 'IS_AJAX' whether the
request was made via AJAX or not
define('IS_AJAX',
isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) ==
'xmlhttprequest');
class My_controller()
{
public function process_form()
{
//Load library form_validation
$this->load->library('form_validation');
//Set some validation rules
$this->form_validation-
>set_rules('Field1','required|xss_clean');
$this->form->validation-
>set_rules('Textarea','required|xss_clean');
if($this->form_validation->run())
{
//Do whatever is needed to process the
form and store the data
...
$data['no_error'] = $this-
>processing_tasks();
Recent Posts
JavaScript:
difference between
null and undefined
How to parallelize
processes in PHP
HMVC: Modular
applications in
CodeIgniter
How to distinguish
uppercase,
lowercase and UTF-
8 characters in
MySQL
JavaScript and CSS
minified with
Carabiner in
CodeIgniter
Archives
August 2014
June 2014
April 2014
March 2014
February 2014
January 2014
10/2/2014 Sending forms with AJAX in CodeIgniter - PHP's Blog
http://phpsblog.agustinvillalba.com/sending-forms-ajax-codeigniter/ 4/7
if(IS_AJAX)
{
$this->load-
>view('ajax_response',$data['no_error']);
}
else
{
//Load standard view
}
}
else
{
//The form is not valid
if(IS_AJAX)
{
$data['message'] =
validation_errors();
$this->load-
>view('ajax_no_valid',$data);
}
else
{
//Load standard view
}
}
}
}
For this, we assume that we have the files ajax_response.php and
ajax_no_valid.php in the views directory of our application with the
following content:
<?php
//ajax_response.php
if($no_error)
{
echo "The for was processed successfully!";
}
else
{
echo "Ooopss! There was some problem trying to
process the form";
}
?>
<?php
December 2013
November 2013
October 2013
September 2013
August 2013
July 2013
June 2013
10/2/2014 Sending forms with AJAX in CodeIgniter - PHP's Blog
http://phpsblog.agustinvillalba.com/sending-forms-ajax-codeigniter/ 5/7
//ajax_no_valid.php
echo $message;
And now jQuery
Now we just need to include the JavaScript code that will send the
forms content via AJAX, preventing the entire page reload:
$(function(){
$('#my_form').submit(function(evnt){
evnt.preventDefault(); //Avoid that the event
'submit' continues with its normal execution, so that,
we avoid to reload the whole page
$.post(url+"my_controller/process_form", //The
variable 'url' must store the base_url() of our
application
$("form#my_form").serialize(), //Serialize all
the content of our form to URL format
function (data) {
$('div#sending_form').prepend(data); //Add
the AJAX response to some div that is going to show
the message
});
});
});
In our jQuery code, we use the function serialize(), which takes care of
encoding all form fields in URL format (a=1&b=2&c=3) and sparing
us having to do it by ourselves one by one. It is remarkable that
serialize() does not encode those fields that do not have the attribute
name, nor serializes the fields like <input type=file />. Here you have
more information about the function serialize()
(http://api.jquery.com/serialize/).
Well, with this you already can send forms via AJAX using jQuery in
CodeIgniter.
Related Posts
SWFUpload in CodeIgniter
Automatic configuration of URL in CodeIgniter
Creating a SOAP server in CodeIgniter
How to distinguish uppercase, lowercase and UTF-8
characters in MySQL
PHPMailer in CodeIgniter
10/2/2014 Sending forms with AJAX in CodeIgniter - PHP's Blog
http://phpsblog.agustinvillalba.com/sending-forms-ajax-codeigniter/ 6/7
ImageFlow in CodeIgniter SWFUpload in CodeIgniter
Share this:
Facebook 8 Twitter 4 Google LinkedIn 2
Email Reddit StumbleUpon Tumblr Pinterest
Pocket Print
Posted in AJAX, CodeIgniter, Development, JavaScript, jQuery, PHP,
Programming Tagged with: ajax, CodeIgniter, development, JavaScript, jQuery,
PHP, programming
Leave a Reply
Your email address will not be published. Required fields are
marked *
Name *
E-mail *
Website
Comment
Y
P T 1
~ #
Like this:
Loading...
10/2/2014 Sending forms with AJAX in CodeIgniter - PHP's Blog
http://phpsblog.agustinvillalba.com/sending-forms-ajax-codeigniter/ 7/7
2014 PHP's Blog Responsive Theme powered by
WordPress

Post Comment
Notify me of follow-up comments by email.
Notify me of new posts by email.
Ads by Info Ad Options

Das könnte Ihnen auch gefallen