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













1 Response to How to create a simple AJAX post in CodeIgniter using Jquery
adzcer
January 22nd, 2010 at 12:54 pm
very concise, salamat.