Codeigniter Ajax Pagination Links Triggers Off-Canvas To Open - ajax

On my ajax below I generate 2 lots of pagination results.
When I click on the pagination links for some reason it triggers my off canvas menu to open.
Question: How can I make sure that only when I click on the class
.navbar-brand will open off canvas?
<script type="text/javascript">
$(document).ready(function() {
var menuToggle = $('.navbar-brand');
var menuToggleIcon = menuToggle.find('.fa');
var offCanvas = $('.offcanvas');
var content = $('.content');
menuToggle.click(function() {
closeMenu(menuToggleIcon, offCanvas);
});
content.click(function() {
closeMenu(menuToggleIcon, offCanvas);
});
function closeMenu(menuToggleIcon, offCanvas) {
menuToggleIcon.toggleClass('fa-indent fa-outdent');
offCanvas.toggleClass('open');
}
});
</script>
<script type="text/javascript">
$(document).ready(function() {
function load_questions_data(page){
$.ajax({
url:"<?php echo base_url(); ?>dashboard/questions_pagination/" + page,
method:"GET",
dataType:"json",
success:function(data) {
$('#questions_table').html(data.questions_table);
$('#question_pagination_link').html(data.pagination1_link);
}
});
}
load_questions_data(1);
$(document).on("click", ".question-pag li a", function(event){
event.preventDefault();
var page = $(this).data("ci-pagination-page");
load_questions_data(page);
});
});
</script>
<script type="text/javascript">
$(document).ready(function() {
function load_users_data(page){
$.ajax({
url:"<?php echo base_url(); ?>dashboard/users_pagination/" + page,
method:"GET",
dataType:"json",
success:function(data) {
$('#users_table').html(data.users_table);
$('#user_pagination_link').html(data.pagination2_link);
}
});
}
load_users_data(1);
$(document).on("click", ".user-pag li a", function(event){
event.preventDefault();
var page = $(this).data("ci-pagination-page");
load_users_data(page);
});
});
</script>
Controller
<?php
class Dashboard extends MY_Controller {
public $data = array();
public function __construct() {
parent::__construct();
$this->load->model('user/user_model');
$this->load->model('forum/question_model');
$this->load->library('pagination');
}
public function index() {
$this->data['title'] = 'Dashboard';
$this->data['is_logged'] = $this->session->userdata('is_logged');
$this->data['navbar'] = $this->load->view('common/navbar', $this->data, TRUE);
$this->load->view('common/header', $this->data);
$this->load->view('common/dashboard', $this->data);
$this->load->view('common/footer', $this->data);
}
public function users_pagination() {
$config = array();
$config["base_url"] = "#";
$config["total_rows"] = $this->user_model->total_users();
$config["per_page"] = 2;
$config["uri_segment"] = 3;
$config["use_page_numbers"] = TRUE;
$config["num_links"] = 1;
$config["full_tag_open"] = '<ul class="pagination user-pag">';
$config["full_tag_close"] = '</ul>';
$config["first_tag_open"] = '<li>';
$config["first_tag_close"] = '</li>';
$config["last_tag_open"] = '<li>';
$config["last_tag_close"] = '</li>';
$config['next_link'] = '>';
$config["next_tag_open"] = '<li>';
$config["next_tag_close"] = '</li>';
$config["prev_link"] = "<";
$config["prev_tag_open"] = "<li>";
$config["prev_tag_close"] = "</li>";
$config["cur_tag_open"] = "<li class='active'><a href='#'>";
$config["cur_tag_close"] = "</a></li>";
$config["num_tag_open"] = "<li>";
$config["num_tag_close"] = "</li>";
$this->pagination->initialize($config);
$page = $this->uri->segment(3);
$start = ($page - 1) * $config["per_page"];
$output = array(
'pagination2_link' => $this->pagination->create_links(),
'users_table' => $this->user_model->get_ajax_users($config["per_page"], $start)
);
echo json_encode($output);
}
public function questions_pagination() {
$config = array();
$config["base_url"] = "#";
$config["total_rows"] = $this->question_model->total_questions();
$config["per_page"] = 2;
$config["uri_segment"] = 3;
$config["use_page_numbers"] = TRUE;
$config["num_links"] = 1;
$config["full_tag_open"] = '<ul class="pagination question-pag">';
$config["full_tag_close"] = '</ul>';
$config["first_tag_open"] = '<li>';
$config["first_tag_close"] = '</li>';
$config["last_tag_open"] = '<li>';
$config["last_tag_close"] = '</li>';
$config['next_link'] = '>';
$config["next_tag_open"] = '<li>';
$config["next_tag_close"] = '</li>';
$config["prev_link"] = "<";
$config["prev_tag_open"] = "<li>";
$config["prev_tag_close"] = "</li>";
$config["cur_tag_open"] = "<li class='active'><a href='#'>";
$config["cur_tag_close"] = "</a></li>";
$config["num_tag_open"] = "<li>";
$config["num_tag_close"] = "</li>";
$this->pagination->initialize($config);
$page = $this->uri->segment(3);
$start = ($page - 1) * $config["per_page"];
$output = array(
'pagination1_link' => $this->pagination->create_links(),
'questions_table' => $this->question_model->get_ajax_questions($config["per_page"], $start)
);
echo json_encode($output);
}
}
Full View
<!-- No Data is currently set inside offcanvas -->
<div class="offcanvas"></div>
<div class="wrap">
<?php echo $navbar;?>
<div class="container-fluid">
<div class="content">
<div class="row">
<div class="col-lg-12">
<div class="page-header">
<h2>Dashboard</h2>
</div>
</div>
</div>
</div>
</div>
<div class="container-fluid">
<div class="content">
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-body">
<div id="questions_table"></div>
<div id="question_pagination_link"></div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-body">
<div id="users_table"></div>
<div id="user_pagination_link"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
function load_questions_data(page){
$.ajax({
url:"<?php echo base_url(); ?>dashboard/questions_pagination/" + page,
method:"GET",
dataType:"json",
success:function(data) {
$('#questions_table').html(data.questions_table);
$('#question_pagination_link').html(data.pagination1_link);
}
});
}
load_questions_data(1);
$(document).on("click", ".question-pag li a", function(event){
event.preventDefault();
var page = $(this).data("ci-pagination-page");
load_questions_data(page);
});
});
</script>
<script type="text/javascript">
$(document).ready(function() {
function load_users_data(page){
$.ajax({
url:"<?php echo base_url(); ?>dashboard/users_pagination/" + page,
method:"GET",
dataType:"json",
success:function(data) {
$('#users_table').html(data.users_table);
$('#user_pagination_link').html(data.pagination2_link);
}
});
}
load_users_data(1);
$(document).on("click", ".user-pag li a", function(event){
event.preventDefault();
var page = $(this).data("ci-pagination-page");
load_users_data(page);
});
});
</script>
<script type="text/javascript">
$(document).ready(function() {
var menuToggle = $('.navbar-brand');
var menuToggleIcon = menuToggle.find('.fa');
var offCanvas = $('.offcanvas');
var content = $('.content');
menuToggle.click(function() {
closeMenu(menuToggleIcon, offCanvas);
});
content.click(function() {
closeMenu(menuToggleIcon, offCanvas);
});
function closeMenu(menuToggleIcon, offCanvas) {
menuToggleIcon.toggleClass('fa-indent fa-outdent');
offCanvas.toggleClass('open');
}
});
</script>

You need to use event.stopPropagation() when you click on a pagination link like,
$(document).on("click", ".question-pag li a", function(event){
event.preventDefault();
event.stopPropagation(); // it will prevent your content click function
var page = $(this).data("ci-pagination-page");
load_questions_data(page);
});
And, for users data
$(document).on("click", ".user-pag li a", function(event){
event.preventDefault();
event.stopPropagation(); // it will prevent your content click function
var page = $(this).data("ci-pagination-page");
load_users_data(page);
});

Thanks to #Rohan Kumar for the answer with pagination links part
I have fixed the problem main problem was here in the off canvas script
New Code
<script type="text/javascript">
$(document).ready(function() {
var menuToggleIcon = $('.navbar-brand').find('.fa');
$('.navbar-brand').on('click', function() {
menuToggleIcon.toggleClass('fa-indent fa-outdent');
$('.offcanvas').toggleClass('open');
});
});
</script>
Old Script
<script type="text/javascript">
$(document).ready(function() {
var menuToggle = $('.navbar-brand');
var menuToggleIcon = menuToggle.find('.fa');
var offCanvas = $('.offcanvas');
var content = $('.content');
menuToggle.click(function() {
closeMenu(menuToggleIcon, offCanvas);
});
content.click(function() {
closeMenu(menuToggleIcon, offCanvas);
});
function closeMenu(menuToggleIcon, offCanvas) {
menuToggleIcon.toggleClass('fa-indent fa-outdent');
offCanvas.toggleClass('open');
}
});
</script>

Related

Laravel 8 filter data with ajax

I want to filter the data in my table. I have seen many tutorials online but do not understand. I found a tutorial that seemed very complicated to me. I just want to use a controller and view. Constants are used in that tutorial and the filter data is static but I don't want to use it and my filter data is dynamic. Help me out as a newbie.
The code of the tutorial is given here
app/Constants/GlobalConstants
<?php
namespace App\Constants;
class GlobalConstants {
const USER_TYPE_FRONTEND = "frontend";
const USER_TYPE_BACKEND = "backend";
const ALL = 'All';
const LIST_TYPE = [self::USER_TYPE_FRONTEND, self::USER_TYPE_BACKEND];
const LIST_COUNTRIES = ["Canada", "Uganda", "Malaysia", "Finland", "Spain", "Norway"];
const SALARY_RANGE = ['401762', '85295', '287072', '456969', '354165'];
}
App/User
public static function getUsers($search_keyword, $country, $sort_by, $range) {
$users = DB::table('users');
if($search_keyword && !empty($search_keyword)) {
$users->where(function($q) use ($search_keyword) {
$q->where('users.fname', 'like', "%{$search_keyword}%")
->orWhere('users.lname', 'like', "%{$search_keyword}%");
});
}
// Filter By Country
if($country && $country!= GlobalConstants::ALL) {
$users = $users->where('users.country', $country);
}
// Filter By Type
if($sort_by) {
$sort_by = lcfirst($sort_by);
if($sort_by == GlobalConstants::USER_TYPE_FRONTEND) {
$users = $users->where('users.type', $sort_by);
} else if($sort_by == GlobalConstants::USER_TYPE_BACKEND) {
$users = $users->where('users.type', $sort_by);
}
}
// Filter By Salaries
if ($range && $range != GlobalConstants::ALL) {
$users = $users->where('users.salary', $range);
}
return $users->paginate(PER_PAGE_LIMIT);
}
App/Http/Controllers/HomeController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use App\Constants\GlobalConstants;
class HomeController extends Controller
{
public function index() {
$users = User::getUsers('', GlobalConstants::ALL, GlobalConstants::ALL, GlobalConstants::ALL);
return view('home')->with('users', $users);
}
public function getMoreUsers(Request $request) {
$query = $request->search_query;
$country = $request->country;
$sort_by = $request->sort_by;
$range = $request->range;
if($request->ajax()) {
$users = User::getUsers($query, $country, $sort_by, $range);
return view('pages.user_data', compact('users'))->render();
}
}
}
view code
#foreach($users as $key)
<div class="card">
<div class="card-header">
<img src="{{ asset('assets/images/dev.png') }}" alt="" />
</div>
<div class="card-body">
<span class="tag tag-pink">{{ $key->type }}</span>
<hr>
<span class="tag tag-salary">Salary: {{ $key->salary }}</span>
<h4>{{ $key->email }}</h4>
<p>
{{ $key->address }}
</p>
<h4>Country: {{ $key->country }}</h4>
<div class="user">
#php
$user=App\User::find($key->id)
#endphp
<img src="{{ asset('assets/images/user-3.jpg') }}" alt="" />
<div class="key-info">
<h5>{{ $user['fullname'] }}</h5>
<small>{{ date('d.m.Y H:i:s', strtotime($key->created_at)) }}</small>
</div>
</div>
</div>
</div>
#endforeach
<script>
$(document).ready(function() {
$(document).on('click', '.pagination a', function(event) {
event.preventDefault();
var page = $(this).attr('href').split('page=')[1];
getMoreUsers(page);
});
$('#search').on('keyup', function() {
$value = $(this).val();
getMoreUsers(1);
});
$('#country').on('change', function() {
getMoreUsers();
});
$('#sort_by').on('change', function (e) {
getMoreUsers();
});
$('#salary_range').on('change', function (e) {
getMoreUsers();
});
});
function getMoreUsers(page) {
var search = $('#search').val();
// Search on based of country
var selectedCountry = $("#country option:selected").val();
// Search on based of type
var selectedType = $("#sort_by option:selected").val();
// Search on based of salary
var selectedRange = $("#salary_range option:selected").val();
$.ajax({
type: "GET",
data: {
'search_query':search,
'country': selectedCountry,
'sort_by': selectedType,
'range': selectedRange
},
url: "{{ route('users.get-more-users') }}" + "?page=" + page,
success:function(data) {
$('#user_data').html(data);
}
});
}
</script>
public function create(Request $request)
{
$doctors = Doctors::all();
$query = doctors_slots::query();
'services.','consultation.')
// ->get();
if($request->ajax()){
$doctors_slots = $query->where(['doc_id'=>$request->doctors])->get();
return response()->json(compact('doctors_slot'));
}
$doctors_slots = $query->get();
return view('Admin.booking.add_booking',compact('doctors','doctors_slots'));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#doctors").on('change', function() {
var doctors = $(this).val();
$.ajax({
url: "{{ route('booking') }}",
type: "GET",
data: {
'doctors': doctors
},
success: function(data) {
var doctors_slots = data.doctors_slots;
var html = '';
if (doctors_slots.length > 0) {
for (let i = 0; i < doctors_slots.length; i++) {
html += '<option value="' + doctors_slots[i][
'available_time_start'
] + '' + doctors_slots[i]['available_time_end'] + '">\
' + doctors_slots[i]['available_time_start'] + ' To\
' + doctors_slots[i]['available_time_end'] + '\
</option>';
}
} else {
html += '<option>No Data Found</option>';
}
$('#option').html(html);
}
});
});
});
</script>

ajax is not able to call the function of codeigniter

This is Welcome controller method
public function send_otp()
{
echo 'in';
die;
$phone = $_POST['mobile'];
if ($phone != '') {
$mobile_detail = $this->welcome_model->check_if_already_mobile_no($phone);
if (!empty($mobile_detail)) {
if ($mobile_detail['is_verified'] == 'yes') {
$message = 'Already Verified.';
echo json_encode(array('status' => 'error', 'message' => $message));
exit;
} else {
$this->welcome_model->delete_mobile_no($phone);
}
}
$otp = self::generateRandomNo();
$this->welcome_model->insert_mobile_detail($phone, $otp);
$link = file_get_contents("http://49.50.67.32/smsapi/httpapi.jsp?username=aplusv&password=aplusv1&from=APLUSV&to=$phone&text=$otp&coding=0");
$status = '';
if ($link != '') {
$status = 'success';
$message = 'Successfully Otp send to your no.';
} else {
$status = 'error';
$message = 'Error in sending OTP.';
}
echo json_encode(array('status' => $status, 'message' => $message));
exit;
}
}
This is model
public function check_if_already_mobile_no($mobile_no = null)
{
$query = $this->db->get_where('mobile_sms', array('mobile_no' => $mobile_no));
return $query->row_array();
}
public function get_mobile_details($mobile_no = null, $otp = null)
{
$query = $this->db->get_where('mobile_sms', array('mobile_no' => $mobile_no, 'otp' => $otp));
return $query->row_array();
}
public function insert_mobile_detail($phone, $otp)
{
$this->mobile_no = $phone;
$this->otp = $otp;
$this->is_verified = 'no';
$this->created_at = date('Y-m-d H:i:s');
$this->db->insert('mobile_sms', $this);
}
This is view
<div class="container" style="margin-top: 25px;">
<div class="row">
<div class="col-md-12" id="response_msg"></div>
<div class="col-md-4" id="enter_mobile">
<form method="POST" action="#">
<div class="form-group">
<label for="phone">Phone </label>
<input type="text" class="form-control" id="mobile" name="phone" placeholder="Enter Mobile">
</div>
<button type="button" name="send_mobile" id="send_otp" class="btn btn-primary">Submit</button>
</form>
</div>
<script src="assets/js/jquery.js"></script>
<script type="text/javascript">
// var base_url = "<?php echo base_url();?>";
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script>
$(function () { // start of doc ready.
$("#send_otp").on('click', function (e) {
var mobile = $('#mobile').val();
alert(mobile);
$.ajax({
url: '<?php echo site_url('index.php/welcome/send_otp'); ?>',
data: {'mobile': mobile},
type: "post",
dataType: 'json',
success: function (data) {
if (data.status == 'success') {
$('#response_msg').html('<div class="alert alert-success" role="alert">' + data.message + '</div>');
$('#mobile_no').val(mobile);
$('#enter_mobile').hide();
$('#verify_otp_form').show();
} else {
$('#response_msg').html('<div class="alert alert-danger" role="alert">' + data.message + '</div>');
}
}
});
});
in ajax is not getting call ie $.ajax is not working here and my controller ie welcome with method send_otp is not called here.
why my function in controller is not getting called
how to solve the issue
what is the proper way to call the controller function using base_url
i have check the console also it is not showing any error
I noticed that you are using site_url() slightly incorrectly: don't write index.php there, just use site_url('welcome/send_otp')
Don't forget you have an unconditional die() at the top of your send_otp method - it will prevent any code below itself from executing

ajax form request from a while - confuse variable

I want to send a form with a button from a while, but I have a problem. If post the button, the form confuse the variable. E.g: i post the button with id 1, and the script get the variable from the last input.
Code:
index:
<?php
$res = getProdus();
foreach($res as $row) { ?>
<form action="addtocart.php" method="POST">
<div class="col-12 col-sm-6 col-md-4 single_gallery_item women wow fadeInUpBig" data-wow-delay="0.2s">
<div class="product-img">
<img src="img/product-img/product-1.jpg" alt="">
<div class="product-quicview">
<i class="ti-plus"></i>
</div>
</div>
<div class="product-description">
<h4 class="product-price">$39.90</h4>
<p>Jeans midi cocktail dress</p>
<input type="hidden" name="addtcart" value="<?=$row['ID'];?>">
<button type="submit" class="add-to-cart-btn">ADD TO CART</button>
</div>
</div>
</form>
<?php } ?>
the ajax request:
$(document).ready(function() {
$('form').submit(function(event) {
var formData = {
'addtcart' : $('input[name=addtcart]').val()
};
$.ajax({
type : 'POST',
url : 'addtocart.php',
data : formData,
dataType : 'json',
encode : true
})
.done(function(data) {
console.log(data);
});
event.preventDefault();
});
});
and the addtocart.php
<?php
include("includes/functions.php");
session_start();
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
if (empty($_POST['addtcart']))
$errors['addtcart'] = 'Este necesar produsul id-ului.';
if ( ! empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
} else {
$ok = AddToCart(filtrare($_POST['addtcart']), getSpec("username", "users", "email", $_SESSION['magazin-user']));
if($ok == 1) {
$data['success'] = true;
$data['message'] = 'Success!';
} else {
$data['success'] = false;
$errors['mysqli'] = "Nu s-a realizat bine query-ul.";
$data['errors'] = $errors;
}
}
echo json_encode($data);
?>
Replace your button code with this
<button type="submit" value="<?=$row['ID'];?>" class="add-to-cart-btn">ADD TO CART</button>
and after that replace you
make changes to your script code
$(".add-to-cart-btn").click(function() {
var formData = {
'addtcart' : $(this).val()
};
.
.
.
and your rest of the code.

file upload is not working with ajax and codeigniter

i have a add form.added data using ajax and codeigniter.there is a file upload in that form.but file is not uploaded.other datas are added.but the file is not uploaded to the specified folder.
View file
<div class="row">
<div class="col-xs-6">
<label for="txtname">Title of Quotation Request :</label>
<input type="text" name="txtTitle" class="form-control" id="txtname" value="<?php
if (!empty($service)) {
echo $service;
}
?>" required>
</div>
<div class="col-xs-6">
<label for="txtcustomer">Select Customer :</label>
<select class="form-control" name="customer" id="customer" required="required">
<option value="">----Select------</option>
<?php
foreach ($customers as $customer) {
echo ' <option value="' . $customer->usr_id . '">' . $customer->usr_name . '</option>';
}
?>
</select>
<input type="hidden" name="" value="sbMerchant">
</div>
<div class="col-xs-12">
<label for="txtattachments">Drawing Attachments :</label>
<input name="txtattachments" type="file" id="txtattachments">
</div>
Ajax function
<script type="text/javascript">
$('#rfqsubmit').click(function () {
//var title = $('#title').val();
alert($('#txtattachments').val());
var form_data = {
title: $('#txtname').val(),
merid: $('#mermerchant').val(),
userid: $('#customer').val(),
description: $('#txtrequirement').val(),
reqid: $('#requirementid').val(),
shipmethod: $('#shipmethod').val(),
shiplocation: $('#shiplocation').val(),
txtattachments: $('#txtattachments').val(),
bidclose: $('#txtbidclose').val(),
shipcurrency:$('#shipcurrency').val(),
txtproduct:$('#txtproduct').val(),
txtunit:$('#txtunit').val(),
txtquantity:$('#txtquantity').val(),
ajax: '1'
};
$.ajax({
url: "<?php echo base_url() ?>moderator/RFQ/addoffline",
type: 'POST',
data: form_data,
dataType:"Json",
success: function(data) {
var last_inserted_id = data.id;
window.location.href ="<?php echo base_url() ?>moderator/RFQ/viewrfq/"+last_inserted_id;
// window.location.href ="<?php //echo base_url() ?>moderator/RFQ/viewrfq/"+ form_data.reqid;
// alert('added Successfully');
}
});
return false;
});
</script>
Controller
public function addoffline() {
$this->load->helper(array('form', 'url'));
$this->load->helper('file');
$ip = $_SERVER['REMOTE_ADDR'];
$config['upload_path'] = 'assets/images/rfqimages';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1000';
$config['max_width'] = '2024';
$config['max_height'] = '1768';
$config['width'] = 75;
$config['height'] = 50;
if (isset($_FILES['txtattachments']['name'])) {
$filename = "-" . $_FILES['txtattachments']['name'];
$config['file_name'] = substr(md5(time()), 0, 28) . $filename;
}
$config['overwrite'] = TRUE;
$config['remove_spaces'] = TRUE;
$field_name = "txtattachments";
$this->load->library('upload', $config);
if (!$this->upload->do_upload('txtattachments')) {
//no file uploaded or failed upload
$error = array('error' => $this->upload->display_errors());
} else {
$dat = array('upload_data' => $this->upload->data());
$this->resize($dat['upload_data']['full_path'], $dat['upload_data']['file_name']);
}
$data7 = array(
'rfq_title' => $this->input->post('title'),
'rfq_detail' => $this->input->post('description'),
'rfq_merchantid' => $this->input->post('merid'),
'rfq_userid' => $this->input->post('userid'),
'rfq_requirementid'=>$this->input->post('reqid'),
'rfq_shipmethod'=>$this->input->post('shipmethod'),
'rfq_shiplocation'=>$this->input->post('shiplocation'),
'rfq_bidclosing'=>strtotime($this->input->post('bidclose')),
'rfq_shipcurrency'=>$this->input->post('shipcurrency'),
'rfq_productid'=>$this->input->post('txtproduct'),
'rfq_unit'=>$this->input->post('txtunit'),
'rfq_quantity'=>$this->input->post('txtquantity'),
'rfq_resource'=>2,
'rfq_dated'=>time(),
'rfq_status'=>0,
'rfq_ipadd'=>$ip
);
$inserted_id= $this->requirement_model->forminsert($data7);
$response=array('id'=>$inserted_id,'message'=>"inserted successfully");
echo json_encode($response);
die();
}
Instead of taking fields like that, do like this
var form_data = new FormData("id of the foem");
Then pass this in ajax like this,
data: form_data,
Make sure, enctype is set for form
enctype="multipart/form-data"
In codeingiter,
<?php echo form_open_multipart('moderator/RFQ/addoffline');?>
Try This:
var formData = new FormData($(this)[0]);
$.ajax({
url: "<?php echo base_url() ?>moderator/RFQ/addoffline",
type: "POST",
data: formData,
async: false,
success:function(data){
var last_inserted_id = data.id;
window.location.href ="<?php echo base_url() ?>moderator/RFQ/viewrfq/"+last_inserted_id;
}
},
cache: false,
contentType: false,
processData: false
});
Check what data is coming inside addoffline() action using
print_r($this->input->post()) and print_r($_FILES) functions. According to your output you can implement your code.
Your problem will be solved.

Making Dependent Combobox in codeigniter project

i am suffering greatly but still unable to make a dependent dropdown box in Codeigniter .
Here is the schema :
groups(group_id,group)
forum(forum_id,subject)
group_forum(group_id,forum_id)
Here is my code :
model
function get_group(){
$query = $this->db->get('group');
return $query->result();
}
function get_subject_by_group($id)
{
$subjects=array();
$this->db->from('forum');
$this->db->join('group_forum','group_forum.forum_id=forum.forum_id','group_id='.$id);
$q=$this->db->get();
foreach($q->result() as $y)
{
$subjects[$y['forum_id']] = $y['subject'];
}
return $subjects;
}
}
Controller:
<?php
class C_control_form extends CI_Controller {
function add_all(){
#Validate entry form information
$this->load->model('Model_form');
$this->form_validation->set_rules('f_group', 'Group', 'trim|required');
$this->form_validation->set_rules('f_forum', 'Forum', 'trim|required');
$data['groups'] = $this->Model_form->get_group(); //gets the available groups for the dropdown
if ($this->form_validation->run() == FALSE)
{
$this->load->view('header_for_combo',$data);
$this->load->view('view_form_all', $data);
$this->load->view('footer_for_combo',$data);
}
else
{
#Add Member to Database
$this->Model_form->add_all();
$this->load->view('view_form_success');
}
}
function get_subjects($group)
{
//echo "hi";
$this->load->model('Model_form');
header('Content-Type: application/x-json; charset=utf-8');
echo (json_encode($this->Model_form->get_subject_by_group($group)));
}
}
?>
View
<html>
<head>
<script type="text/javascript" src="<?php echo base_url("js/jquery-1.7.2.min.js"); ?>" ></script>
<script type="text/javascript">
// $('#f_group, #f_forum').hide();
$(document).ready(function(){
$('#f_group').change(function(){
var group_id = $('#f_group').val();
if (group_id != ""){
var post_url = "index.php/c_control_form/get_subjects/"+group_id;
// var post_url = "<?php echo base_url();?>"+"c_control_form/get_subjects"+group_id;
$.ajax({
type: 'POST',
url: post_url,
dataType : 'json',
success: function(subjects) //we're calling the response json array 'cities'
{
$("#f_forum > option").remove();
// $('#f_forum').empty();
// $('#f_forum, #f_forum_label').show();
$.each(subjects,function(forum_id,subject)
{
var opt = $('<option/>'); // here we're creating a new select option for each group
opt.val(forum_id);
//alert(id);
opt.text(subject);
$('#f_forum').append(opt);
});
} //end success
}); //end AJAX
} else {
$('#f_forum').empty();
// $('#f_forum, #f_forum_label').hide();
}//end if
}); //end change
});
</script>
</head>
<body>
<?php echo form_open('c_control_form/add_all'); ?>
<p>
<label for="f_group">Group<span class="red">*</span></label>
<select id="f_group" name="f_group">
<option value=""></option>
<?php
foreach($groups as $group){
echo '<option value="' . $group->group_id . '">' . $group->group_name.'</option>';
}
?>
</select>
</p>
<p>
<label for="f_forum">Subject<span class="red">*</span></label>
<select id="f_forum" name="f_forum" id="f_forum_label">
<option value=""></option>
</select>
</p>
<?php echo form_close(); ?>
</body>
Please change
$subjects[$y['forum_id']] = $y['subject'];
to
$subjects[$y->forum_id] = $y->subject;
in the model file. Also spaces or newlines in model php file after and before the php tags.
EDIT: Added below
function(subjects){
var select = $('#f_forum').empty();
$.each(subjects.values, function(i,item) {
select.append( '<option value="'
+ item.id
+ '">'
+ item.name
+ '</option>' );
});

Resources