How to use x-editable with CodeIgniter? - codeigniter

I would like to understand using x-editable in my CodeIgniter first project. I tried to read x-editable docs but I'm beginner in JavaScript too so I can't understand
I make simple controller to collect data from JavaScript but I didn't complete it or data not updated in database.
$('#username').editable({
type: 'text',
pk: 1,
url: '/post',
title: 'Enter username'
});
How to get submitted data in controller or model to process database update query
I want to passing data submitted from x-editable to model to update it in database.

You can follow this simple steps
Assume that $userId = 5 ; $username = "admin";
Consider you html look like this
<a type="text" name="username" onclick="setEditable(this);" data-pk="<?php echo $userId ;?>" data-placeholder="Enter Username" data-name="username" data-type="text" data-url="<?php echo site_url();?>user/updateUserName" data-value="<?php echo $username ;?>" data-prev="admin" data-title="Enter Username"><?php $username; ?></a>
In Javascript code write following
$.fn.editable.defaults.mode = 'inline';
function setEditable(obj) {
$(obj).editable({
emptytext: $(obj).attr('data-value'),
toggle: 'dblclick',
mode: 'inline',
anim: 200,
onblur: 'cancel',
validate: function(value) {
/*Add Ur validation logic and message here*/
if ($.trim(value) == '') {
return 'Username is required!';
}
},
params: function(params) {
/*originally params contain pk, name and value you can pass extra parameters from here if required */
//eg . params.active="false";
return params;
},
success: function(response, newValue) {
var result = $.parseJSON(response);
$(obj).parent().parent().find('.edit-box').show();
$(obj).attr('data-value', result.username);
$(obj).attr('data-prev', result.username);
},
error: function(response, newValue) {
$(obj).parent().parent().find('.edit-box').hide();
if (!response.success) {
return 'Service unavailable. Please try later.';
} else {
return response.msg;
}
},
display: function(value) {
/*If you want to truncate*/
var strName = strname !== '' ? strname : $(obj).attr('data-value');
var shortText = '';
if (strName.length > 16)
{
shortText = jQuery.trim(strName).substring(0, 14).split("").slice(0, -1).join("") + "...";
}
else {
shortText = strName;
}
$(this).text(shortText);
}
});
$(obj).editable('option', 'value', $(obj).attr('data-value'));
}
In Controller site
<?php
class User extends CI_Controller
{
function __construct()
{
parent::__construct();
}
function updateUserName()
{
$this->load->model('user_model');
if ($this->input->is_ajax_request()) {
$valueStr = $this->input->get_post('value') ? $this->input->get_post('value') : '';
$new_nameStr = trim($valueStr);
$result_arr['username'] = $new_nameStr;
$userId = $this->input->get_post('pk') ? $this->input->get_post('pk') : '';
$data['username'] = $new_nameStr;
$result_arr['username'] = $new_nameStr;
$this->user_model->userUpdateFunction($data, $userId);
}
echo json_encode($result_arr);
exit;
}
}
You can change editable mode , i have set inline only

First of all, this question is about AJAX and JavaScript/jQuery, not Codeigniter.
Basically, the code that you wrote is about posting data with AJAX. First, you need to create a controller and model, then you can post data with AJAX. I'm adding a sample code:
Controller file:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Sample extends CI_Controller {
function __construct() {
parent::__construct();
$this ->load ->model('modelfolder/sample_model');
}
public function index() {
$this->sample_model->sampleFunction();
}
}
Model File:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Sample_model extends CI_Model {
function sampleFunction() {
$data = array('fieldName' => $this->input->post('userName', TRUE));
$this->db->where('id', $this->input->post('userId', TRUE));
$this->db->update('tableName', $data);
return true;
}
}
routes.php File:
$route['demoPost'] = 'controller_folder/sample';
View File's HTML part:
<form id="sampleForm">
<input type="text" name="userId" />
<input type="text" name="userName" />
</form>
View File's AJAX part:
$(document).ready(function(){
$("#sampleForm").submit(
function(){
$.ajax({
type: "POST",
url: "<?php echo site_url('demoPost'); ?>",
data: $("#sampleForm").serialize(),
});
});
});

Related

laravel using jQuery Ajax | Ajax Cart

I'm Trying to Save The Product into The Database By Clicking On Add To Cart
But It's Not Adding I Also Use Ajax `
I Want To Add The Cart To DataBase And It's Not Adding.
This is The Error That I cant Add Any Product To The Cart Because Of It
message: "Call to undefined method App\User\Cart::where()", exception: "Error",…
enter image description here
Model Page.
class Cart extends Model
{
use HasFactory; I
protected $table = 'carts';
protected $fillable = [
'user_id',
'prod_id',
'prod_qty',
];
}
Controller page.
public function addToCart(Request $request)
{
$product_qty = $request->input('product_qty');
$product_id = $request->input ('product_id');
if(Auth::check())
{
$prod_check = Product::where('id',$product_id)->first();
if($prod_check)
{
if(Cart::where('prod_id',$product_id)->where('user_id',Auth::id())->exists())
{
return response()->json(['status' => $prod_check->pname." Already Added to cart"]);
}
else
{
$cartItem - new Cart();
$cartItem->user_id = Auth::id();
$cartItem->prod_qty = $product_qty;
$cartItem->save();
return response()->json(['status' => $prod_check->pname." Added to cart"]);
}
}
}
else{
return response()->json(['status' => "Login to Continue"]);
}
}
javascript page.
This Is MY First Time To Use Ajax And Sure That Every Thing Is Correct I Want Know Why Its Not Add
$('.addToCartBtn').click(function (e) {
e.preventDefault();
var product_id = $(this).closest('.product_data').find('.prod_id').val();
var product_qty = $(this).closest('.product_data').find('.qty-input').val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
method: "POST",
url: "/add-to-cart",
data: {
'product_id': product_id,
'product_qty': product_qty,
},
success: function (response) {
alert(response.status);
}
});
// alert(product_id);
// alert(product_qty);
// // alert ("test ") ;
});
Route:
Route::middleware(['auth'])->group(function () {
Route::post('/add-to-cart', [App\Http\Controllers\User\indexController::class, 'addToCart' ]);});
So why this error occurs, how can I fix it?`
This look like an error in importation like App\Models\Cart not like this?
verify if you had added use App\Models\Cart;

how to send ajax request to codeigniter library file or class

ajax code
function autocomplet(){
var countryname= $('#countrysearch').val();
$.ajax({
type: 'POST',
url: 'My_commonlib', // My_commonlib is library file in library folder
data: "countryname=" + countryname,
success: function(data){
}
});
}
html code
<input type="text" onkeyup="autocomplet()" class="inputs form-control " style=" border-bottom: .5px solid;" id="countrysearch" name="countrysearch" placeholder=" Search">
I send a request to My_commonlib in library folder
php code
Pass ajax request to this class My_commonlib or method getcountry
class My_commonlib {
private $ci;
public function __construct()
{
$this->ci=& get_instance();
$this->ci->load->database();
// parent::__construct();
}
function getcountry(){
$this->ci->db->from('countries');
$this->ci->db->order_by("country", "ASC");
return $this->ci->db->get()->result();
}
}
and get in view file as
$a = new My_commonlib();
$results=$a->getcountry();
foreach ($results as $row)
{ ?>
<?php echo $row->country ; ?><br>
<?php }
?>
Change :
url: 'My_commonlib',
to
url: '<?php echo base_url('My_commonlib/getcountry');?>',
CodeIgniter uses the url to decide which controller to load. You will always handle requests with a controller. The controller can be a very thin object that loads the library and passes the request on to it.

Dropdown using Ajax in Codeigniter

Can't find the error, it has to be with the query at "comunas" data base.
Here are the codes:
1) The 2 tables:
comunas:
comId comNombre comRegion
regiones:
regId regNombre
2) Controller:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Usuarios extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->database();
$this->load->helper('form');
$this->load->helper('url');
$this->load->model("regiones_model");
$this->load->model("comunas_model");
}
public function index_get()
{
$data['regionDrop'] = $this->getRegiones();
//loads up the view with the query results
$this->load->view('panel/usuario_agrega_view',$data);
}
public function getRegiones()
{
$this->db->select('regId,regNombre');
$this->db->from('regiones');
$query = $this->db->get();
// the query mean select cat_id,category from category
foreach($query->result_array() as $row){
$data[$row['regId']]=$row['regNombre'];
}
// the fetching data from database is return
return $data;
}
public function getComunaByRegion($regId=string)
{
$this->db->select('comId,comNombre, comRegion');
$this->db->from('comuna');
$this->db->where('comRegion',$regId);
$query = $this->db->get();
return $query->result();
}
//call to fill the second dropdown with the comunas
public function buildDropComunas()
{
//set selected country id from POST
echo $regId = $this->input->post('id',TRUE);
//run the query for the comunas we specified earlier
$districtData['districtDrop']=$this->comunas_model->getComunaByRegion($regId);
$output = null;
foreach ($districtData['districtDrop'] as $row)
{
//here we build a dropdown item line for each query result
$output .= "<option value='".$row->comNombre."'>".$row->comNombre."</option>";
}
echo $output;
}
}
3) Models: I'm not using the querys at models, I can't "touch them" for now, so I'm putting that code direct in the controller.
4) View:
<script type="text/javascript">
$(document).ready(function() {
$("#regionesDrp").change(function(){
/*dropdown post *///
$.ajax({
url:"<?php echo base_url();?>usuarios/buildDropComunas",
data: {id: $(this).val()},
type: "POST",
success:function(data){
$("#comunaDrp").html(data);
}
});
});
});
</script>
<!--country dropdown-->
<?php
echo form_dropdown('regionesDrp', $regionDrop,'','class="required" id="regionesDrp"'); ?>
I tried to follow the example from: http://www.c-sharpcorner.com/uploadfile/225740/cascading-drop-down-in-codeigniter-using-ajax/
But I have a different database (FK comId) and as I told you, I can't use a model file for this. Anyway, I tried with a region_model and comuna_model but it's the same.
Use append() not html()
$("#comunaDrp").append(data);
First of all, the function getComunaByRegion should be:
public function getComunaByRegion($comRegion=string)
{
$this->db->select('comId,comNombre');
$this->db->from('comunas');
$this->db->where('comId',$comRegion);
$query = $this->db->get();
return $query->result();
}
Plus, in the controller, the function public function buildDropComunas_post() wasn't called with POST, that was the main reason of my 404 not found.

Codeigniter inline edit not working

I created the following code, but do not run. Can you help?
My Controller
public function updateDb()
{
//$this->load->model('user_m');
$this->page_m->inline($_POST['file_description']);
return;
}
My Model
public function inline( $file_description, $id ){
$this->db->set($data)->where($this->$id, $page['file_description'])->update($this->file);
}
Form
<?php echo $file->file_description?>
Jquery
function showEdit(file_description) {
$(file_description).css("background","#FFF");
}
function save(file_description) {
$(file_description).css("background","#FFF url(<?php echo base_url('assets/img/loaderIcon.gif');?>loaderIcon.gif) no-repeat right");
$.ajax({
url: "<?php echo base_url()?>index.php/admin/page/updateDb",
type: "POST",
id : '<?php echo $page->id;?>',
name : 'file_description'
});
}
Looks like you're not passing the ID to your model which it requires.
public function inline( $file_description, $id ){...}
$this->page_m->inline($_POST['file_description'], $_POST['id']);
You could use $this->input->post() though...

Ajax changing the entire sql query

http://rimi-classified.com/ad-list/west-bengal/kolkata/electronics-and-technology
The above link has a filter in the left. I am trying to use ajax to get city from state. but as the ajax is triggered the entire query is changing.
SELECT * FROM (`ri_ad_post`)
WHERE `state_slug` = 'west-bengal'
AND `city_slug` = 'kolkata'
AND `cat_slug` = 'pages'
AND `expiry_date` > '2014-03-21'
ORDER BY `id` DESC
It is taking the controller name in the query (controller name is pages).
The actual query is:
SELECT *
FROM (`ri_ad_post`)
WHERE `state_slug` = 'west-bengal'
AND `city_slug` = 'kolkata'
AND `cat_slug` = 'electronics-and-technology'
AND `expiry_date` > '2014-03-21'
ORDER BY `id` DESC
// Controller
public function ad_list($state,$city,$category,$sub_cat=FALSE)
{
if($state===NULL || $city===NULL || $category===NULL)
{
redirect(base_url());
}
$data['ad_list'] = $this->home_model->get_adlist($state,$city,$category,$sub_cat);
$this->load->view('templates/header1', $data);
$this->load->view('templates/search', $data);
$this->load->view('ad-list', $data);
$this->load->view('templates/footer', $data);
}
public function get_cities()
{
$state_id = $this->input->post('state');
echo $this->city_model->get_cities($state_id);
}
// Model
public function get_adlist($state,$city,$category,$sub_cat=FALSE)
{
if ($sub_cat === FALSE)
{
$this->db->where('state_slug', $state);
$this->db->where('city_slug', $city);
$this->db->where('cat_slug', $category);
$this->db->where('expiry_date >', date("Y-m-d"));
$this->db->order_by('id', 'DESC');
$query = $this->db->get('ad_post');
}
$this->db->where('state_slug', $state);
$this->db->where('city_slug', $city);
$this->db->where('cat_slug', $category);
$this->db->where('sub_cat_slug', $sub_cat);
$this->db->where('expiry_date >', date("Y-m-d"));
$this->db->order_by('id', 'DESC');
$query = $this->db->get('ad_post');
return $query->result_array();
//echo $this->db->last_query();
}
//ajax
<script type="text/javascript">
$(document).ready(function () {
$('#state_id').change(function () {
var selState = $(this).val();
alert(selState);
console.log(selState);
$.ajax({
url: "pages/get_cities",
async: false,
type: "POST",
data : "state="+selState,
dataType: "html",
success: function(data) {
$('#city').html(data);
$("#location_id").html("<option value=''>--Select location--</option>");
}
})
});
});
</script>
Please help me how to solve this issue. Please check the url I have provided and try to select a state from the filter section the problem will be more clear.
In .js what is the value of selState ?
In your model, you should if() else() instead of just a if, because your query will get override.
Where is the get_cities function ? Can we see it ?
On your url, the problem is that your ajax url doesn't return a real ajax call but an entire HTML page which is "harder" to work with. Try to change it into json (for dataType's ajax()) You should only do in your php something like this :
in your controller :
public function get_cities()
{
$state = $this->input->post('state');
//Do the same for $cat
if (!$state) {
echo json_encode(array('error' => 'no state selected'));
return 0;
}
$get_cities = $this->model_something->getCitiesByStateName($state);
echo json_encode($get_cities);
}
You should definitely send with ajax the $cat info

Resources