20Dec
How to create a simple AJAX post in CodeIgniter using Jquery
Posted by admin as CodeIgniter, JQuery, Javascript/AJAX, PHP
This article will show and explain to you how to fire a simple AJAX request in CodeIgniter using Jquery.In this example we will have a form,with username and password field on it,check if the fields are empty and validate it against a correct username and password.You can check out the demo by clicking here.
Note:Database interactions and CodeIgniter’s form validation is not included in this tutorial, and it is up to you to use the functions mentioned in your own application when you will need it.This tutorial only shows how data is passed and returned via AJAX in your CodeIgniter application.
What we will need:
Latest version of CodeIgniter Web Application Framework.
Latest version of Jquery Javascript Framework.
Where to place your javascript files
Let’s create a folder named js and put it in the root directory of your CodeIgniter application,where your system/ folder resides.We’ll tackle on how to call them later.
The controller
<?php
class Ajax_post extends Controller {
function Ajax_post()
{
parent::Controller();
$this->load->helper(array('url'));
}
function index()
{
$this->load->view('ajax_post');
}
function post_action()
{
if(($_POST['username'] == "") || ($_POST['password'] == ""))
{
$message = "Please fill up blank fields";
$bg_color = "#FFEBE8";
}elseif(($_POST['username'] != "myusername") || ($_POST['password'] != "mypassword")){
$message = "Username and password do not match.";
$bg_color = "#FFEBE8";
}else{
$message = "Username and password matched.";
$bg_color = "#FFA";
}
$output = '{ "message": "'.$message.'", "bg_color": "'.$bg_color.'" }';
echo $output;
}
}
?>
We will load the url helper of CI because we will using it in the view,when calling the javascript files.function index() will load the ajax_post view page and function post_action() is the action of the form in the ajax_post view.
post_action() function is simply an if-else statement if the fields are empty,and if the input values matches with the correct ones.In this case,we will set the correct value of username = “myusername” and password = “mypassword”.If the output is negative(blank fields,no match),it will generate an error message and the bg_color,which we will use in coloring the message box in the view later will produce somewhat like a red color, otherwise bg_color will be “#FFA” , somewhat like a yellow color and message will be a positive one.
We will pass the $message and $bg_color variable back into the view by using JSON.
The view
<html>
<head>
<script language="javascript" src="<?php echo base_url(); ?>js/jquery-1.3.2.min.js"></script>
<script language="javascript" src="<?php echo base_url(); ?>js/ajax_post.js"></script>
<title>Demo Page</title>
<style type="text/css">
body {
background-color: #fff;
margin: 40px;
font-family: Lucida Grande, Verdana, Sans-serif;
font-size: 14px;
color: #4F5155;
}
a {
color: #003399;
background-color: transparent;
font-weight: normal;
}
h1 {
color: #444;
background-color: transparent;
border-bottom: 1px solid #D0D0D0;
font-size: 16px;
font-weight: bold;
margin: 24px 0 2px 0;
padding: 5px 0 6px 0;
}
code {
font-family: Monaco, Verdana, Sans-serif;
font-size: 12px;
background-color: #f9f9f9;
border: 1px solid #D0D0D0;
color: #002166;
display: block;
margin: 14px 0 14px 0;
padding: 12px 10px 12px 10px;
}
#form_message{
display:none;
text-align:center;
margin-bottom:5px;
padding:10px;
}
</style>
</head>
<body>
<h1>This is the demo page for the simple AJAX post in CodeIgniter Using JQuery</h1>
<p>Username: myusername | Password: mypassword</p>
<p>Try to enter nothing in the fields and click the Submit button.<br/>
Try to mismatch the username and/or password and click the Submit button. </p>
<div style="text-align:right; width:500px;" >
<div id="form_message"></div>
<form name="ajax_form" id ="ajax_form" method="post">
Username/Email:*<input type="text" name="username" id="username" size="30" /><br/><br/>
Password:*<input type="password" name="password" id="password" size="30" /><br/><br/>
<input type="submit" value="Submit" name="login_submit" id="login_submit" />
</form>
</div>
</body>
</html>
This is how we call the javascript files in the view.base_url() is what you had specified in your config file.Change your $config['base_url'] depending on your needs.In this case the jquery core and my jquery file is inside the js folder at the root of my CI application.
<script language="javascript" src="<?php echo base_url(); ?>js/jquery-1.3.2.min.js"></script>
<script language="javascript" src="<?php echo base_url(); ?>js/ajax_post.js"></script>
We will display the message in this div and the backround color of it depends on the output.It’s set to display:none;
<div id="form_message"></div>
the Jquery file - ajax_post.js
$(document).ready(function(){
$("#login_submit").click(
function(){
var username=$("#username").val();
var password=$("#password").val();
$.ajax({
type: "POST",
url: "http://demos.ryantetek.com/codeigniter_samples/index.php/ajax_post/post_action",
dataType: "json",
data: "username="+username+"&password="+password,
cache:false,
success:
function(data){
$("#form_message").html(data.message).css({'background-color' : data.bg_color}).fadeIn('slow');
}
});
return false;
});
});
We will trigger the function when the Submit button with id login_submit is clicked.
$("#login_submit").click
We put the values of the input boxes into variables for easy readability purposes.
var username=$("#username").val();
var password=$("#password").val();
The AJAX method type of submitting is via POST.The url parameter is the action of the form.dataType of the output is JSON,like what I had mentioned in explaining the output in the controller.We pass data variables via the data parameter.If the ajax request is successfull,we will put the message inside the form_message div with the value of “data.message”. data.message is the $message in post_action()
in the controller.Change the background-color of the div using the bg_color output, and adds a little animation, fading in a slow speed.
$.ajax({
type: "POST",
url: "http://localhost/codeigniter_samples/index.php/ajax_post/post_action",
dataType: "json",
data: "username="+username+"&password="+password,
cache:false,
success:
function(data){
$("#form_message").html(data.message).css({'background-color' : data.bg_color}).fadeIn('slow');
}
});
Always return false to avoid submitting when the Submit button is clicked.
return false;
Basically,that’s it.Hoped you had learned from this articel and continue to explore many different ways in combining the power of JQuery and CodeIgniter. Like what I had said earlier,database and validation functions is not included in this tutorial,it is up to you to use other functions depending on your needs.See you!
- Tags: AJAX in CodeIgniter, AJAX in CodeIgniter tutorial, AJAX post in CodeIgniter using JQuery, form submit in CodeIgniter via AJAX, How to use Jquery in COdeIgniter tutorial, JSON in CodeIgniter, Retrieve JSON data in AJAX post, Using JQuery and CodeIgniter together, Using JQuery CodeIgniter and JSON, Using Jquery in CodeIgniter, Using Jquery in CodeIgniter tutorial













24 Responses to How to create a simple AJAX post in CodeIgniter using Jquery
adzcer
January 22nd, 2010 at 12:54 pm
very concise, salamat.
j2ibeo
March 18th, 2010 at 9:57 am
very good! matsala.
Musta
July 19th, 2010 at 4:16 am
Very good tutorial for beginners who want to get an idea of the ajax implemtation via jquery. Thanx
Anes P.A
September 27th, 2010 at 2:39 pm
Hi Friends.
For me this Example is not work properly, problem is cannot include the
both js files in my codeigniter localhost . I take all content from both files
and paste same page it’s Work nicely. I try all methods to include the
js files, but don’t get any idea. Please give me a helping hand to include
js files in that view… email id is : anes(dot)pa(at)gmail.com
Tahnkfully Anes
admin
September 28th, 2010 at 11:02 pm
Hello Anes,
Put the js folder(with the js files of course) in the root folder of your CI application. It is where your system folder resides also. Kindly look at the head part of my script to understand what I’m trying to explain.
Thanks,
Ryan
Benjamin Vison
October 28th, 2010 at 6:55 am
Hi, your script its very interesting…I’m working on something i would really appreciate some help!, i want a script that the admin could be able to delete an entry (in this case an image) without refreshing the page and same time removing the element from view, i’m very new at dealing with ajax so i hope you can make a simple demo and from there i can make it on my own!! thanks in advice to anyone!!
Thanks,
Benjamin
Benjamin Vison
October 28th, 2010 at 6:57 am
I’m using codeigniter by the way, sorry i didn’t mention it.
kaichi
November 18th, 2010 at 12:08 pm
very nice tutz… there’s a lot of tutz about CI & Ajax out there but yours is alot clearer.. thanks man!
admin
November 18th, 2010 at 10:52 pm
Thanks kaichi for appreciating!
Satish
May 9th, 2011 at 6:30 pm
Thanks.
seb0093
July 4th, 2011 at 10:31 am
hello
Can you explain me which Controller you refer when you call :
class Ajax_post extends Controller
I have an Error CI can’t find Controller. because that controller doesn’t exist.
Should I create a php file named controller in controller file , I really don’t undrestand
admin
July 4th, 2011 at 11:03 am
you should name the file as ajax_post.php to eliminate the error.
rodsil
July 16th, 2011 at 7:25 pm
i was wondering.. is the password here encrypted? because firebug can see the post variable and anything you send can be read. do you have any idea to secure the password during post.. like having it encrypted or something. I’m looking for tutorials over the net yet haven’t been able to have one I could easily use.
admin
July 18th, 2011 at 8:06 am
hello Rodsil,
Why not try securing the password during registration of the user? here’s a tutorial about it: http://www.ryantetek.com/2009/11/how-to-create-a-better-and-more-secure-password-hashing-function-in-php
Securing the password during post is not included in this tutorial, just demoing how AJAX can simply be implemented in CodeIgniter. Thanks!
Marvin
October 7th, 2011 at 4:22 pm
Thank you for the tutorial. I am however trying to output a table from my controller in the function post_action(). I can output simple text but as soon as i do something like $message = “my values”; then it does not work. Any idea how i can go around this?
Marvin
October 7th, 2011 at 4:23 pm
My html tags were kicked out of my previous message. But “my values” was inside a table
Shibbir
November 26th, 2011 at 12:22 am
haven’t try it yet. but looks like it’s a really easy to understand tutorial. Thank u very much
McCubo
November 26th, 2011 at 3:46 am
Thank you so much! really works
(with some modifications to my needs) Thank you and keep going.
Sekai
November 28th, 2011 at 2:43 am
Googd One
ana
January 2nd, 2012 at 9:35 am
it works for me, but after success, how can i forward the url to a certain page? thanks
admin
January 2nd, 2012 at 7:59 pm
try to look at window.location function of Javascript and place it under the success function of the AJAX response. Glad this article helped you in some way
Kevin McCutceon
April 25th, 2012 at 6:40 am
Hello, I like this entry, I really need it to work and I see how it is going to work.
My problem is that something is wrong with the POST action in Jquery.min it’s saying, did anyone come across this problem also?
Plus the
{
parent::Controller();
$this->load->helper(array(’url’));
}
Part crashes the page, Im not sure how old this post is but maybe it has changed with the update of CI.
Any help would be greatly appreciated
wsm
May 14th, 2012 at 7:11 pm
very informative…thanks!
websolutionsmantra.com
madhab
December 27th, 2012 at 5:47 pm
it helped me.. thanks admin