how to send ajax request to codeigniter library file or class - ajax

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.

Related

Codeigniter: AJAX request don't have response data

I have a simple app in codeigniter. In my view I have ajax POST request to the controller, but I don't receive response data. I checked in the chrome dev tool in network tab the response and the message is: No response data available for this request :
My view:
<table class="table table-striped table-bordered">
<thead>
<tr>
<td>First</td>
<td>Sec</td>
<td>Th</td>
<td>Th</td>
</tr>
</thead>
<tbody>
<?php
if(isset($result))
{
foreach($result as $value)
{
echo "<tr><td>". $value->cai . "</td><td>". $value->partner ."</td><td>". $value->spot ."</td><td><button type='button' id='".$value->cai."' class='btn btn-danger delete'>Delete</button></td></tr>";
}
}
?>
</tbody>
</table>
<?php echo $this->pagination_bootstrap->render(); ?>
<script>
$('.table').on('click','.delete',function(){
var id=$(this).attr('id');
var confirm_box=confirm('Sure?');
if(confirm_box === true)
{
$.ajax({
url: '<?php echo site_url('Tires_Crud/deleteCai'); ?>',
type: 'POST',
data: {
key: id
},
dataType: 'json',
success: function(data) {
console.log(JSON.parse(data));
}
});
}
});
</script>
My controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Tires_Crud extends MY_Controller
{
public function deleteCai()
{
$status = array(
"STATUS" => "true"
);
return json_encode($status);
}
}
In my config file CSRF protection is DISABLED! Because when its enabled the ajax request is not working. Thanks for your help in advance!
Some issues with this code.
#1: The way you're forming the ajax request. Where you have type: 'POST' should be method: 'POST' - but more than a typo, it's important that you understand these are referred to as the HTTP method - same way you'd specify that in a <form method='post' tag. If you don't provide a method, it's assumed to be GET.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods
Also, because you specified dataType:'json' - jquery will deliver a ready to use parsed JSON object. No need for you to parse it yourself
$.ajax({
url: '<?php echo site_url('Tires_Crud/deleteCai'); ?>',
method: 'POST', // <-- change this from 'type' to 'method'
data: {
key: id
},
dataType: 'json',
success: function(data) {
// console.log(JSON.parse(data)); // <-- no need to parse - you have set dataType to be json, which means it will come to you already parsed
console.log(data);
})
#2 - In your PHP, you'd catch your key variable (you sent in ajax) with $_POST['key'] - though in codeigniter you get it like this:
// codeigniter 2.x and 3.x
$this->input->post('key');
// codeigniter 4
use CodeIgniter\HTTP\IncomingRequest;
$request = service('request');
$request->getPost('key');
#3 - With ajax, you actually echo the response, rather than return it:
public function deleteCai(){
$status = array(
"STATUS" => "true"
);
echo json_encode($status);
}

Post 403 forbidden on Yii2 Ajax Call

I know there's other topic on this in stackoverflow but it still didn't work for me. I try to make a simple dynamic menu that generate dynamic content based on the chosen <li> id.
This is the code to generate the menu :
foreach($cabang as $index=>$model){
echo '<li id='.$model->idDpd->id_dpd.'>
<a class="nav-link" href="#" role="tab" data-toggle="tab">'.$model->idDpd->dpd.'</a>
</li>';
}
The menu is created successfully. But I have the problem with the content generated with Ajax
This is what I have in my view file :
$script = <<< JS
$(document).ready(function(){
function load_page_details(id)
{
$.ajax({
url: "<?=Url::to(['/site/fetch']) ?>",
method:"POST",
data:{id:id}, //pass the 'id' of Load_page_details function parameter to the targeted URL
success:function(data)
{
$('#page_details').html(data);
}
});
}
//load page-details where the id in the database table equals 1. Set the default to 1 while page is loading for the first time.
/* load_page_details(1);*/
$('.nav li').click(function(){
var page_id = $(this).attr("id");
load_page_details(page_id);
});
});
JS;
$this->registerJs($script)
?>
This is my SiteController and the action :
public function actionFetch(){
if (Yii::$app->request->isAjax) {
// fetch the $_POST["id"]
$data = Yii::$app->request->post('id');
if(isset($data))
{
$query= Cabang::find()->where(['id_dpd'=> $data])
->joinWith('idDpd')
->all();
$output = '';
foreach($query as $model)
{
$output .= '
<div role="tabpanel" class="col-lg-4 tab-pane fade show active" >
<div class="col-md-12">
<h4>'.$model->kota.'</h4>
<p>'.$model->alamat.'</p>
<p>'.$model->telp.'</p>
<p>'.$model->email.'</p>
<p>'.$model->jadwal.'</p>
</div>
</div>
';
}
/* echo $output;*/
// return Json
return \yii\helpers\Json::encode($output);
}
}
}
The error caught in my console in chorome dev tool : jquery.js:9175 POST http://localhost/%3C?=Url::to([%27/site/fetch%27])%20?%3E 403 (Forbidden)
I tried to make the fetch function to a new php file and link the URL in my Ajax to that file (not to a controller or SiteController in my case) like : url: url:"site/fetch.php",but it returned jquery.js:9175 POST http://localhost/site/fetch.php 404 (Not Found)
What am I doing wrong? I have spent two days without solution. Thanks for the help!
Your PHP is not correct - you cannot use <?= /* ... */ ?> inside of heredoc. You need to use temporary variable:
$url = Url::to(['/site/fetch']);
$script = <<<JS
$(document).ready(function () {
function load_page_details(id) {
$.ajax({
url: "$url",
method: "POST",
data: {id: id}, //pass the 'id' of Load_page_details function parameter to the targeted URL
success: function (data) {
$('#page_details').html(data);
}
});
}
$('.nav li').click(function () {
var page_id = $(this).attr("id");
load_page_details(page_id);
});
});
JS;
$this->registerJs($script);

Codeigniter form validatiion with ajax not work

I try to test the controller validation without ajax and it worked.
I try to test ajax out side form validation and it work.
but when I try to get form validation result in ajax it not work.
Tris is my controller
function ajax_form() {
$this->load->helper('form');
$this->load->view('ajax/ajax_input');
}
function test() {
$this->load->library('form_validation');
$this->form_validation->set_rules('myname', 'Name', 'required');
if ($this->form_validation->run() == TRUE) {
echo 1;
} else {
echo validation_errors();
}
}
This is my view
<div id="test"></div>
<?php
echo form_open('ajax/test', array('id'=>'sub'));
echo form_input('myname');
echo form_submit('submit','Submit');
echo form_close();
?>
<script>
$(document).ready(function(){
$('#sub').submit(function(event){
event.preventDefault();
$.ajax({
url:'test',
type:'POST',
data:{myname:$('#myname').val()},
success:function(data)
{
console.log(data);
}
});// end ajax
});//end btn click
});//end ready
</script>
I already spent 3 hours try to fix this but still not work. Hope u guy can help.
Update type.

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...

How to use x-editable with 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(),
});
});
});

Resources