Codeigniter Tutorials
- What is codeigniter?
- Application_Architecture
- MVC Architecture
- HMVC Architecture
- Codeigniter Configuration
- Remove index.php from url in codeigniter
- MVC Concept
- View
- Alternate PHP Syntax for View Files
- Routing
- Codeigniter URL
- Get Current URL
- Previous page URL get
- Seo Friendly URL
- Slug Create in codeigniter
- What is _remap() function
- Remove controller name from url in codeigniter
- Codeigniter Controller Class
- Class Constructor
- GET $ POST method in Codeigniter
- Models
- Basepath, Apppath, FCPATH
- URI Segment
- Page Redirect
- Helper class
- Custom Helper class
- Form Helper
- Common Helper Functions
- Common Function
- Array Problems
- Call controller in Helper
- Add active class to menu using Helper class
- Custom Library
- Custom Library Example
- when to use get_instance()
- Codeigniter Hook
- how to work inline css in codeigniter
- Custom 404 page
- 404 custom error page
- Create custom config file in codeigniter
- How to set and get config item value
- How to Speed Up CodeIgniter App?
- Codeigniter Functions
- Session
- cookies
- How to Set & Get Tempdata in Codeigniter
- flash messages in Codeigniter
- Flashdata
- Encryption and Decryption In CodeIgniter
- Codeigniter security
- csrf token form security
- Password Hashing
- Form Validation
- Custom Validation
- Registration Form with validation
- Server Side Form Validation
- Validate Select Option Field
- Date Format Validation
- Date Format change in codeigniter
- Date Functions
- DOB Validation
- CI CRUD
- User SignUp
- User Login
- User Logout
- Login Account
- Login form with RememberMe
- Login Form with session
- User change password
- Change Password with Callback Validation to Check Old Password
- Forgot password
- Reset password
- Insert data in database
- Fetch data from database
- Update data in database
- Delete data in database
- File Upload
- Image Upload with resize Image
- Upload Multiple file and images
- Upload Multiple images with CRUD
- File and image update
- Upload Image Using Ajax.
- Email Send
- Email Send Using Email library
- Email Send Using SMTP Gmail
- Notification send
- store data in json format in DB
- Json parse
- Fetch data Using Ajax with Json data
- How to Show data Using Ajax with Json parse
- Get JSON Data from PHP Script using jQuery Ajax
- Insert data Using Ajax
- Submit data Using Ajax with form validation
- How to show data Using Ajax in codeigniter
- Insert & Update Using Ajax
- Registration Form With Validation Using Ajax in codeigniter
- Delete data Using Ajax Confirmation
- Delete All data Using checkbox selection
- Ajax CSRF Token
- Ajax Post
- Ajax serverside form validation
- Contact form using AJAX with form validation
- DataTable Using Ajax dynamically
- DataTables pagination using AJAX with Custom filter
- DataTables AJAX Pagination with Search and Sort in codeigniter
- DataTables in Codeigniter using Ajax
- Ajax Custom Serarch
- Ajax Live Data Search using Jquery PHP MySql
- Ajax Custom Serarch and sorting in datatable
- Dynamic Search Using Ajax
- Autocomplete using jquery ajax
- Jquery Ajax Autocomplete Search using Typeahead
- Dynamic Dependent Dropdown Using Ajax
- Dynamic Dependent Dropdown list Using Ajax
- Dynamic Dependent Dropdown in codeigniter using Ajax
- ajax username/email availability check using JQuery
- Check Email Availability Using Ajax
- Data Load on mouse scroll
- Ajax CI Pagination
- Pagination in codeigniter
- Ajax Codeigniter Pagination
- email exists or not using ajax with json
- CRUD using AJAX With Modal popup in CI
- Add / Show Data on modal popup using Ajax
- Modal popup Validation using Ajax
- Data show on Modal popup Using Ajax
- Add / Remove text field dynamically using jquery ajax
- How to Add/Delete Multiple HTML Rows using JavaScript
- Delete Multiple Rows using Checkbox
- Multiple Checkbox value
- Form submit using jquery Example
- REST & SOAP API
- Multi-Language implementation in CodeIgniter
- How to pass multiple array in view
- Captcha
- create zip file and download
- PhpOffice PhpSpreadsheet Library (Export data in excel sheet)
- data export in excel sheet
- Excel File generate in Codeigniter using PHPExcel
- Dompdf library
- tcpdf library
- Html table to Excel & docs download
- CI Database Query
- Database Query
- SQL Injection Prevention
- Auth Model
- Join Mysql
- Tree View in dropdown option list
- OTP Integration in codeigniter
- curl post
- download file using curl
- Sweet Alert
- Sweet alert Delete & Success
- Log Message in Codeigniter
- Menu & Submenu show dynamically
- Set Default value in input box
- Cron Jobs
- Stored Procedure
- Display Loading Image when AJAX call is in Progress
- Send SMS
- IP Address
- Codeigniter Tutorialspoint
- Website Link
- How To Create Dynamic Xml Sitemap In Codeigniter
- Paypal Payment Integration
- Get Latitude and Longitude From Address in Codeigniter Using google map API
- How To Create Simple Bar Chart In Codeigniter Using AmCharts?
- dynamic Highcharts in Codeigniter
- Barcode in Codeigniter
- Codeigniter Interview Questions
- Project
Home » Codeigniter »
Insert and show data using Ajax request.
File name : Insert_Record_Ajax.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Insert_Record_Ajax extends CI_Controller {
public function __construct() {
parent::__construct();
}
public function index()
{
$data['data'] = $this->db->get("items")->result();
$this->load->view('itemlist', $data);
}
public function add_record()
{
$data = array(
'title' => $this->input->post('title'),
'description' => $this->input->post('description')
);
$this->db->insert('items', $data);
echo 'Added successfully.';
}
}
File name : itemlist.php
<!DOCTYPE html>
<html>
<head>
<title>codeigniter ajax request - itsolutionstuff.com</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>codeigniter ajax request - itsolutionstuff.com</h2>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-8">
<strong>Title:</strong>
<input type="text" name="title" class="form-control" placeholder="Title">
</div>
<div class="col-lg-8">
<strong>Description:</strong>
<textarea name="description" class="form-control" placeholder="Description"></textarea>
</div>
<div class="col-lg-8">
<br/>
<button class="btn btn-success">Submit</button>
</div>
</div>
<table class="table table-bordered" style="margin-top:20px">
<thead>
<tr>
<th>Title</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<?php foreach ($data as $item) { ?>
<tr>
<td><?php echo $item->title; ?></td>
<td><?php echo $item->description; ?></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<script type="text/javascript">
$("button").click(function(){
var tit = $("input[name='title']").val();
var des = $("textarea[name='description']").val();
$.ajax({
//url: '/ajax-requestPost',
url: "<?php echo base_url();?>" + "Insert_Record_Ajax/add_record",
type: 'POST',
data: {title: tit, description: des},
error: function() {
alert('Something is wrong');
},
success: function(data) {
$("tbody").append("<tr><td>"+tit+"</td><td>"+des+"</td></tr>");
alert("Record added successfully");
}
});
});
</body>
</html>
CREATE TABLE IF NOT EXISTS `items` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL,
`description` varchar(255) NOT NULL,
`created_at` datetime NOT NULL,
`updated_at` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=
Insert Record into db using jquery with ajax
File name : index.php
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('button').on('click', function(e) {
//$('form[name="frm"]').serializeArray();
var datastring = $("#frm").serialize();
//alert(datastring);
$.ajax({
type: "POST",
url: "<?php echo base_url();?>addleaderinfo/insert_leader_info",
data: datastring,
success: function(data) {
//alert(data);
alert("Data submited Successfully");
setTimeout(function(){
location.reload();
}, 100);
/* setInterval(function() {
var randomnumber = Math.floor(Math.random() * 100);
$('#frm').text(
'I am getting refreshed every 3 seconds..! Random Number ==> '
+ randomnumber);
}, 2000);*/
},
error: function(data) {
//alert("error!");
}
});
})
});
</script>
</head>
<body>
<div class="row">
<center>
<div style="color: red;">
<?php //echo validation_errors(); ?>
</div>
</center>
<h3 class='flashMsg flashSuccess' style="color: green;">
<?=$this->session->flashdata('msg')?>
</h3>
<h3 class='flashMsg flashSuccess' style="color: green;">
<?php //echo $error;?>
</h3>
<form class="form-horizontal"
action="" method="post" name="frm" id="frm">
<div class="col-md-6">
<input type="text" class="form-control" name="name" /> <input
type="text" class="form-control" name="partyname" /> <input
type="text" class="form-control" name="email" /> <input
type="text" class="form-control datepicker" name="dob"> <input
type="radio" class="" name="gender" value="male"> Male
<input type="radio" class=""
name="gender" value="female"> Female
<input type="text" class="form-control" name="mob" /> <select class="form-control select" name="qualification">
<option value="">--- Select ---</option>
<option value="B.A">B.A</option>
</select> <select class="form-control select" name="state">
<option value="">--- Select state ---</option>
<option value="delhi">delhi</option>
</select>
<textarea class="form-control" rows="6" name="details"></textarea>
<button class="btn btn-primary" type="button"
name="submit" id="submit">Submit</button>
</div>
</form>
</div>
</body>
</html>
Controller
File name : Addleaderinfo.php
<?php
defined('BASEPATH') OR exit('no direct access allowd');
class Addleaderinfo extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
$this->load->view('admin_views/header');
$this->load->view('admin_views/leftpanel');
$this->load->view('admin_views/addleaderinfo');
$this->load->view('admin_views/footer');
}
public function insert_leader_info()
{
$data = array(
'candidate_name' => $this->input->post('name'),
'party_name ' => $this->input->post('partyname'),
'email' => $this->input->post('email'),
'dob'=> $this->input->post('dob'),
'gender' => $this->input->post('gender'),
'mobile' => $this->input->post('mob'),
'qualification'=> $this->input->post('qualification'),
'state'=> $this->input->post('state'),
'details'=> $this->input->post('details')
);
$this->Admin_model->leader_insert($data);
$success = "Your data is successfully submited.";
$this->session->set_flashdata('msg', '<div class="alert alert-danger text-center">Your data is successfully submited.</div>');
redirect('Addleaderinfo');
exit;
}
}
Auth_model
File name : Auth_model.php
public function leader_insert($data)
{
$this->db->insert('politician_info', $data);
}
File name :
Submit Form Using Ajax
File name :
<html>
<head>
<title>AJAX Form Submit without Page Refresh</title>
</head>
<body>
<form id="myForm">
<input type="text" name="name" placeholder="Enter your name" required />
<input type="text" name="email" placeholder="Email ID" required />
<input type="text" name="city" placeholder="City" required />
<input type="submit" name="submit" value="Submit Form" />
</form>
<div id="postData"></div>
<script src="js/jquery-1.10.2.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#myForm').submit(function(e){
e.preventDefault();
$.ajax({
url: "get_data.php",
type: "POST",
data: $(this).serialize(),
success: function(data){
$("#postData").html(data);
},
error: function(){
alert("Form submission failed!");
}
});
});
});
</script>
</body>
</html>
File name : get_data.php
<?php
echo json_encode($_POST);
?>
How to Submit data using ajax with success message?
File name :
<!DOCTYPE html>
<html lang="en">
<head>
<title>Register</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h1 align="center">Application Form</h1>
<div class="alert alert-success alert-dismissible" id="success" style="display:none;">
<a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
</div>
<div class="form-group">
<label for="email">Name:</label>
<input type="text" class="form-control" id="name" placeholder="Enter Name" name="name">
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" placeholder="Enter Email" name="email">
</div>
<div class="form-group">
<label for="email">Phone:</label>
<input type="text" class="form-control" id="phone" placeholder="Enter Phone" name="phone">
</div>
<div class="form-group">
<label for="email">City:</label>
<input type="text" class="form-control" id="city" placeholder="Enter City" name="city">
</div>
<button type="submit" class="btn btn-primary" id="butsave">Submit</button>
</div>
<script>
$(document).ready(function() {
$('#butsave').on('click', function() {
var name = $('#name').val();
var email = $('#email').val();
var phone = $('#phone').val();
var city = $('#city').val();
var password = $('#password').val();
if(name!="" && email!="" && phone!="" && city!=""){
$("#butsave").attr("disabled", "disabled");
$.ajax({
url: "<?php echo base_url("ajax_controller/savedata");?>",
type: "POST",
data: {
type: 1,
name: name,
email: email,
phone: phone,
city: city
},
cache: false,
success: function(dataResult){
/*
var data = JSON.parse(dataResult);
if(data.statusCode==200){
$("#butsave").removeAttr("disabled");
$('#fupForm').find('input:text').val('');
$("#success").show();
$('#success').html('Data added successfully !');
//alert("Success");
}
else if(data.statusCode==201){
alert("Error occured !");
}
*/
//alert(dataResult);
var data = JSON.parse(dataResult);
$("#success").show();
$('#success').html(data.msg);
// $("#result").addClass("alert alert-success");
// $('#success').html(dataResult);
}
});
}
else{
alert('Please fill all the field !');
}
});
});
</script>
</body>
</html>
Controller
File name : Ajax_controller.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Ajax_controller extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
$this->load->view('ajax-register');
}
public function savedata()
{
if($this->input->post('type')==1)
{
$name=$this->input->post('name');
$email=$this->input->post('email');
$phone=$this->input->post('phone');
$city=$this->input->post('city');
$this->Auth_model->saverecords($name,$email,$phone,$city);
//echo json_encode(array("statusCode"=>200));
echo json_encode(array("msg"=>"Thankyou for submitting Data"));
// echo "Thank you";
}
}
}
Model
File name : Auth_model.php
function saverecords($name,$email,$phone,$city)
{
$query="INSERT INTO `crud`( `name`, `email`, `phone`, `city`)
VALUES ('$name','$email','$phone','$city')";
$this->db->query($query);
}
Example :- How to submit data using ajax with success message?
File name : view
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Ajax Form Submission in Codeigniter </title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/additional-methods.min.js"></script>
<style>
.error{ color:red; }
</style>
</head>
<body>
<div class="container">
<h2 style="margin-top: 10px;">Codeigniter Ajax Form Submission <a href="https://ittutorial.in" target="_blank">ittutorial</a></h2>
<br>
<br>
<form id="ajax_form" method="post" action="javascript:void(0)">
<div class="form-group">
<label for="formGroupExampleInput">Name</label>
<input type="text" name="name" class="form-control" id="formGroupExampleInput" placeholder="Please enter name">
</div>
<div class="form-group">
<label for="email">Email Id</label>
<input type="text" name="email" class="form-control" id="email" placeholder="Please enter email id">
</div>
<div class="form-group">
<label for="mobile_number">Mobile Number</label>
<input type="text" name="mobile_number" class="form-control" id="mobile_number" placeholder="Please enter mobile number" maxlength="10">
</div>
<div class="alert alert-success d-none" id="msg_div">
<span id="res_message"></span>
</div>
<div class="form-group">
<button type="submit" id="send_form" class="btn btn-success">Submit</button>
</div>
</form>
</div>
<script>
if ($("#ajax_form").length > 0) {
$("#ajax_form").validate({
rules: {
name: {
required: true,
maxlength: 50
},
mobile_number: {
required: true,
digits:true,
minlength: 10,
maxlength:12,
},
email: {
required: true,
maxlength: 50,
email: true,
},
},
messages: {
name: {
required: "Please enter name",
maxlength: "Your last name maxlength should be 50 characters long."
},
mobile_number: {
required: "Please enter contact number",
minlength: "The contact number should be 10 digits",
digits: "Please enter only numbers",
maxlength: "The contact number should be 12 digits",
},
email: {
required: "Please enter valid email",
email: "Please enter valid email",
maxlength: "The email name should less than or equal to 50 characters",
},
},
submitHandler: function(form) {
$('#send_form').html('Sending..');
$.ajax({
url: "<?php echo base_url('ajax/store') ?>",
type: "POST",
data: $('#ajax_form').serialize(),
dataType: "json",
success: function( response ) {
console.log(response);
console.log(response.success);
$('#send_form').html('Submit');
$('#res_message').html(response.msg);
$('#res_message').show();
$('#msg_div').removeClass('d-none');
document.getElementById("ajax_form").reset();
setTimeout(function(){
$('#res_message').hide();
$('#msg_div').hide();
},10000);
}
});
}
})
}
</script>
</body>
</html>
Controller
File name :
<?php
class Ajax extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('Form_model');
$this->load->helper('url_helper');
$this->load->helper('form');
$this->load->library('form_validation');
}
public function create()
{
$data['title'] = 'jQuery Ajax Form';
$this->load->view('jquery-ajax/jquery-ajax-form', $data);
}
public function store()
{
$insert = $this->Form_model->create();
$data = array('success' => false, 'msg'=> 'Form has been not submitted');
if($insert){
$data = array('success' => true, 'msg'=> 'Form has been submitted successfully');
}
echo json_encode($data);
}
}
Model
File name :
<?php
class Form_model extends CI_Model {
public function __construct()
{
$this->load->database();
}
public function create()
{
$this->load->helper('url');
$data = array(
'name' => $this->input->post('name'),
'mobile_number' => $this->input->post('mobile_number'),
'email' => $this->input->post('email')
);
$insert = $this->db->insert('users', $data);
if ($insert) {
return $this->db->insert_id();
} else {
return false;
}
}
}
File name :