Display id using ajax to controller - php

Hello I am new in ci and i want to pass is from view to controller in codeigniter using ajax. if i add dataType : 'json', then my ajax can not work and i want to echo data from controller
<script type="text/javascript">
$(document).ready(function() {
$(".cart").click(function(){
var subid=$(this).attr('data-index');
alert(subid);
$.ajax({
url: '<?php echo site_url(); ?>/Home/add_to_cart',
type: "POST",
data: {
subid: subid
},
dataType:'json',
success: function(data) {
window.location.href = '<?php echo base_url(); ?>index.php/Home/add_to_cart';
alert(data);
},
error: function(xhr, status, error) {
var error=xhr.responseText;
// alert(error);
}
});
});
});
</script>
Controller
I want to echo the category id when the ajax can send the request
$category_id = $this->input->post('subid');
echo json_encode($category_id);

Well here is all information what Freshers need to handle in CodeIgniter :)
First remove 'index.php' from CodeIgniter url via .htaccess. Create .htaccess file where CodeIgniter 'index.php' exist.
.htaccess (Using windows, just rename any blank text file as .htaccess. to create a .htaccess file, So easy ...)
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php/$0 [PT,L]
</IfModule>
How to enable mode_rewrite in WAMP
How to enable mode_rewrite in WAMP manualy
1 - Open apache’s configuration file using your favorite text editor.
2 - The configuration file generally locates at:{apache_dir}/conf/httpd.conf
3 - If you are using XAMPP or WAMP package then you will find the file
at:{xampp_dir}/bin/apache/apache-xxx/conf/httpd.conf or {wamp_dir}/bin/apache/apache-xxx/conf/httpd.conf
4 - Search for the following string:#LoadModule rewrite_module modules/mod_rewrite.so and uncomment it (remove the ‘#’ sign).
5 - Now search for another string AllowOverride None and replace it by AllowOverride All
6 - Finally Save the changes, close your text editor and Restart your apache server.
Set 'base_url' automatically
/*
|--------------------------------------------------------------------------
| Dynamic Base Url
|--------------------------------------------------------------------------
| Put below code in 'index.php' on top
|
*/
define('APP_URL', ($_SERVER['SERVER_PORT'] == 443 ? 'https' : 'http') . "://{$_SERVER['SERVER_NAME']}".str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']));
Config Settings
/*
|--------------------------------------------------------------------------
| Base Site URL
|--------------------------------------------------------------------------
|
| URL to your CodeIgniter root. Typically this will be your base URL,
| WITH a trailing slash:
|
| http://example.com/
|
| If this is not set then CodeIgniter will guess the protocol, domain and
| path to your installation.
|
*/
$config['base_url'] = APP_URL;
/*
|--------------------------------------------------------------------------
| Index File
|--------------------------------------------------------------------------
|
| Typically this will be your index.php file, unless you've renamed it to
| something else. If you are using mod_rewrite to remove the page set this
| variable so that it is blank.
|
*/
$config['index_page'] = '';
Config CSRF Settings (If you are not passing CSRF token in form, or not using CodeIgniter Form Helper. Otherwise you will not able to POST param or call Controller Method via ajax or Form POST)
$config['csrf_protection'] = FALSE;
Now, Questions Answer :(
JavaScript
<script type="text/javascript">
$(document).ready(function() {
// define base url
var _CI_BASE_URL_ = "<?php echo site_url(); ?>";
/**
* ---------------------------
* Example -1 with Url Params
* ---------------------------
*/
// on click cart button call ajax
$(".cart").click(function(e){
// stop default button behaviour
e.preventDefault();
// get subid from button attr
var subid = $(this).data('index');
// ajax function
$.ajax(
{
// *Notice: just send 'subid' with ajax url and CodeIgniter will take it from url
url: _CI_BASE_URL_ + 'home/add_to_cart/' + subid,
// method
type: "POST",
// data type
dataType:'json',
// success callback
success: function(data) {
// why server response, we already have subid in JavaScript vars
// we can user that same to redirect in url
window.location.href = _CI_BASE_URL_ + 'home/add_to_cart/' + subid;
},
// ohh! we got error
error: function(xhr, status, error) {
// get ajax error
var error = xhr.responseText;
alert('Request made some error: ' + error);
}
});
});
/**
* ---------------------------
* Example -2 with POST Params
* ---------------------------
*/
// on click cart button call ajax
$(".cart").click(function(e){
// stop default button behaviour
e.preventDefault();
// get subid from button attr
var subid = $(this).data('index');
// ajax function
$.ajax(
{
// just send subid with url and CodeIgniter will take from url
url: _CI_BASE_URL_ + 'home/add_to_cart_another',
// method
type: "POST",
// POST params
data: {subid: subid},
// data type
dataType:'json',
// success callback
success: function(data) {
// if got the JSON with key cat_id
if(data.cat_id){
// if you want to alert, first alert then redirect
alert('CodeIginter retuned Cat ID: ' + data.cat_id);
// redirect user now..
window.location.href = _CI_BASE_URL_ + 'home/add_to_cart_another/' + data.cat_id;
}else{
alert('Category ID not return or null...');
}
},
// ohh! we got error
error: function(xhr, status, error) {
// get ajax error
var error = xhr.responseText;
alert('Request made some error: ' + error);
}
});
});
});
</script>
Now CodeIgniter Controller :( :(
<?php
// Security First Matters...
(defined('BASEPATH') or exit('No direct script access allowed'));
/**
* Class Home CI Controller
*/
class Home extends CI_Controller
{
/**
* Default run method
* #return [type] [description]
*/
public function index()
{
$this->load->view('home');
}
/**
* [add_to_cart description]
* #param [type] $cat_id [description]
*/
public function add_to_cart($cat_id)
{
/**
* Codeigniter is enough smart to take parameters if passed in url
* if url is 'http://localhost/CodeIgniter/home/add_to_cart/100'
* '100' will be assign to $cat_id by CodeIgniter
*
* intval to make sure only integer
*/
// echo response for ajax call as JSON
echo json_encode(array('cat_id' => intval($cat_id)));
}
/**
* [add_to_cart description]
* #param [type] $cat_id [description]
*/
public function add_to_cart_another()
{
/**
* get cat id from post and sanitize by passing 2nd param as true for XSS Clean,
* Security always matters...
*
* intval to make sure only integer
*/
$cat_id = $this->input->post('subid', true);
// echo response for ajax call as JSON
echo json_encode(array('cat_id' => intval($cat_id)));
}
}
/* End of file home.php */
/* Location: ./application/controllers/home.php */
Now, I am going to sleep.. :D Tada!! ....

It is very simple, In your Controller funtion add_to_cart just do it like this:
$category_id = $this->input->post('subid');
echo $category_id;
Just dont add json_encode() of it.
Then if you want to return to your ajax request just do it like this
success: function(data) {
alert(data);
},
That should be work.
just comment if it is not work.
Thanks,

In Controller echo with header like this
php :
header("Content-Type: application/json", true);
echo json_encode(array('id'=>$category_id));
Ajax : change your success function code order
success: function(data) {
console.log(data);
temp = JSON.parse(data);
alert(temp.id);
//window.location.href = '<?php echo base_url(); ?>index.php/Home/add_to_cart';
},

Try this
$.ajax({
type:'POST',
url:'<?php echo base_url();?>.'/Home/add_to_cart',
data:{'subid':subid},
success:function(data){
//location.reload();
}
});

Related

Failed to load resource: the server responded with a status of 500, Codeigniter project

I'm trying to send a call using ajax but in Chrome it is rising error but in firefox there is no error. But still it can't calling the method.
THis append shows 7 divs, but some div gets loaded but some of div keeps loading and console shows error 500
//get recent posts via ajax controller class
public function get_recent_articles($cr_post_id,$category,$limit,$offset)
{
$recent_post=$this->Post_model->get_recent_articles($cr_post_id,$category,$limit,$offset);
return $this->output
->set_content_type('application/json')
->set_status_header(200)
->set_output(json_encode($recent_post));
}
Here is view part
$('#recent_post_cat_2').show();
$('#recent_post_cat_2').append('<div id="recent_post_cat_2_preloader" class="col-md-12 col-sm-12 text-center" style="vertical-align:middle;padding:15px 0px;"><i class="fa fa-spinner fa-spin" style="font-size:24px"></i></div>');
Here is Ajax function
/* START - get_recent_articles*/
function get_recent_articles(category,div_id,limit)
{
//prepare url
url="<?php echo "/./home-recent-articles-filter-cat/";?>"+category+"/"+limit+"/"; $.ajax({
url: url,
type: 'GET',
dataType: "json",
crossDomain: true,
success: function(data){
// console.log(JSON.stringify(data));
if(data.status=="success")
{
prepared_posts_data=prepare_cards(category,data.data,3);
$(div_id+'_preloader').remove();
$(div_id).append(prepared_posts_data);
$(div_id).show();
var myLazyLoad = new LazyLoad({
threshold: 50,
callback_load: function(e) {
// console.log($(e).attr("data-original") + " loaded" );
}
});
}
else{
console.log("no posts available");
}
}
});
}
I suspect this line
url="<?php echo "/./home-recent-articles-filter-cat/";?>"+category+"/"+limit+"/";
Codeigniter URL does not look like this. It contains at least 3 parameters on it(unless index function)
base URL
controller name
method name
So it should be something like this
url = <?= base_url(); ?>.'controller_name/get_recent_articles'
Make sure these are loaded
URL helper
short_tag=On in PHP.ini
Check these
Set up the base URL in codeigniter

Using Ajax to Access Controller Method in Symfony

I have a form type that uses a twig template and in that twig, I get the images attached to the current listing object and display them along with an option to delete them for the user. I'd like to be able to have it where the user can delete the images individually without the page refreshing so I'm trying to trigger the controller method using Ajax.
scripts.js
$('.delete_image').on('click', function(e) {
$.ajax({
type: 'POST',
url: '/delete_image',
data: ({
listing_id: $('#listing_id').val(),
imageName: 'nature-forest-trees-158251.jpg'
}),
success: function(response) {},
error: function(jqXHR, textStatus, errorThrown) {
alert('status code: ' + jqXHR.status + 'errorThrown: ' + errorThrown + 'jqXHR.responseText:' + jqXHR.responseText);
}
})
})
imageName is just a placeholder value (of the image I'm debugging) and in my controller I have
ListingController.php
/**
* #Route("/delete_image", name="delete_image")
* #Method({"GET", "POST"})
* #ParamConverter("listing", class="DirectoryPlatform\AppBundle\Entity\Listing")
*/
public function deleteImage(Request $request, Listing $listing) {
// $listing_id = (isset($_POST['listing'])) ? $_POST['listing'] : -1;
// $imageName = (isset($_POST['imageName'])) ? $_POST['imagename'] : -1;
$listing_id = $request->get('listing');
$imageName = $request->get('imageName');
$this->get('punk_ave.file_uploader')->removeFiles(array('folder' => 'tmp/attachments/' . $listing->getId() . '/'. $imageName));
exit(0);
}
I've tried using $_POST[] as well as $request->get() to no avail. I could maybe use inline scripting but it's something I want to avoid for the sake of best coding practices.
The way to get POST variables inside a controller is:
$listing_id = $request->request->get('listing');
However in your case I would be sceptical if I should use AJAX requests in the sense that you could avoid the overhead of AJAX calls, by manipulating properly the DOM (remove for example an image from the DOM when delete button clicked, without taking any action at the server) and finally submit all the changes together by submitted your form and then remove the deleted images from your entity.
This last call could as well be an AJAX call.

AJAX request delete column base on their id.

Good day. I'm working on a admin page basically it is a content management system. I want to delete the data based on their id. But unfortunately i've encounter a error on the htpp request. here is the error.
Request URL: admin/ajax_delete
Request Method:POST
Status Code:500 Internal Server Error
Remote Address:144.76.136.165:8181
VIEW FILE:
<span class="glyphicon glyphicon-trash"></span>
$("#delete_tpi").click(function() {
alert("Are you sure you want to delete?");
var tpi = $('.datatpi').val(); //package includes
var did = $('#data-id').val();
$.ajax({
url: '<?php echo site_url('admin/ajax_delete'); ?>',
type: 'POST',
datatype: 'html',
data: {id: did, tpi: tpi},
success:function (b){
if (b == 'Success') {
$('.#data-id').val('');
$('.datatpi').val('');
location.reload();
}
}
});
});
$('body').on('click','.edit-content-modal',function(){
var id = $(this).attr('data-id');
$('#data-id').val(id);
});
Controller file:
public function ajax_delete(){
$did = $this->input->post('id');
$ptpi = $this->input->post('tpi');
$update = $this->products_model->row_delete($did,$ptpi);
var_dump($update);
echo ($update)?'Success':'Fail';
}
MODEL FILE:
function ajax_delete($did,$ptpi){
$this->db->where('id',$did);
$this->db->delete('products',$ptpi);
return $this->db->affected_rows() > 0;
}
Because <a></a> element does not expect a value tag. You can get the ID of the clicked #delete_tpi link by using attr():
var did = $("#delete_tpi").attr('data-id');
Your POST request to admin/ajax_delete returns 500 Internal Server Error. This is a server-side error. If you use codeigniter, take a look at application/logs/*.log files that will give you detail information about the error.
I think, your problem is calling a non-existing function from model:
In your controller, you have:
$this->products_model->row_delete($did,$ptpi);
But your model, contains:
function ajax_delete($did,$ptpi){
....
}
Do you have row_delete() function in your model?
Once again, i suggest you to look at logs file, because many problems can result in server-side error.

403 Forbidden Access to CodeIgniter controller from ajax request

Im having trouble with sending an ajax request to codeigniter controller. It is throwing back a 404 Forbidden Access error. I have found some sort of similar question to this but im not sure if its particular to CodeIgniter framework, and also the solution give in that thread did not solve my problem. below is my ajax request. Im wondering this is probably because of the .htaccess of the root folder of CI Application folder, but i dont want to change its default configuration yet.
Is sending ajax request to CI controller the correct way of implementing this? if not, any suggestion please. Thanks!
var ajax_load = '{loading gif img html}';
var ajax_processor = 'http://localhost/patientcare-v1/application/controller/ajax_processor/save_physical_info';
$("#save").click(function(){
$("#dialog-form").html(ajax_load);
$.post(
ajax_processor,
$("#physical-info").serialize(),
function(responseText){
$("#dialog-form").html(responseText);
},
"json"
);
});
CodeIgniter use csrf_protection, you can use it with Ajax and JQuery simply.
This (ultimate ?) solution work on multiple Ajax request (no 403 ;-) and preserve the security).
Change the configuration
Open the file /application/config/config.php
and change the line $config['csrf_token_name'] by :
$config['csrf_token_name'] = 'token';
You can use another name, but change it everywhere in future steps.
Add CSRF in your Javascript
Add script in a view; for me is in footer.php to display the code in all views.
<script type="text/javascript">
var CFG = {
url: '<?php echo $this->config->item('base_url');?>',
token: '<?php echo $this->security->get_csrf_hash();?>'
};
</script>
This script create an object named CFG. This object can be used in your Javascript code. CFG.url contain the url of your website and CFG.token ... the token.
Automatically renew the CSRF
Add this code in your part $(document).ready(function($){---}) as
$(document).ready(function($){
$.ajaxSetup({data: {token: CFG.token}});
$(document).ajaxSuccess(function(e,x) {
var result = $.parseJSON(x.responseText);
$('input:hidden[name="token"]').val(result.token);
$.ajaxSetup({data: {token: result.token}});
});
});
This script initialize the CSRF token and update it everytime when a request Ajax is sended.
Send the CSRF in PHP
I've created a new controller, named Ajax. In CodeIgniter, the link to use it is http://www.domain.ltd/ajax/foo
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Ajax extends CI_Controller {
public function foo() {
$this->send(array('foo' => 'bar'));
}
private function send($array) {
if (!is_array($array)) return false;
$send = array('token' => $this->security->get_csrf_hash()) + $array;
if (!headers_sent()) {
header('Cache-Control: no-cache, must-revalidate');
header('Expires: ' . date('r'));
header('Content-type: application/json');
}
exit(json_encode($send, JSON_FORCE_OBJECT));
}
}
The send function add the CSRF automatically and transform an array in object.
The final result
Now, you can use Ajax with JQuery very simply !
$.post(CFG.url + 'ajax/foo/', function(data) {
console.log(data)
}, 'json');
Result :
{"token":"8f65cf8e54ae8b71f4dc1f996ed4dc59","foo":"bar"}
When the request get data, the CSRF is automatically updated to the next Ajax request.
Et voilà !
Remove the <code> and application/controller from your ajax_processor like,
var ajax_processor = 'http://localhost/patientcare-v1/index.php/ajax_porcessor/save_physical_info';
If you are hiding index.php from url by using htaccess or routing then try this url,
var ajax_processor = 'http://localhost/patientcare-v1/ajax_porcessor/save_physical_info';
I was facing same problem but now I have fixed this problem.
First of all, I have created csrf_token in header.php for every pages like below code
$csrf = array(
'name' => $this->security->get_csrf_token_name(),
'hash' => $this->security->get_csrf_hash()
);
<script type="text/javascript">
var cct = "<?php echo $csrf ['hash']; ?>";
</script>
After that, when we are sending particular value through ajax then we will have to sent csrf token like below code
$.ajax({
url:"<?php echo APPPATHS.'staff_leave/leaveapproval/getAppliedLeaveDetails'; ?>",
data:{id:id,status:status,'<?php echo $this->security->get_csrf_token_name(); ?>': cct},
method:"post",
dataType:"json",
success:function(response)
{
alert('success');
}
});
I hope this code will help you because this is working for me.
// Select URIs can be whitelisted from csrf protection (for example API
// endpoints expecting externally POSTed content).
// You can add these URIs by editing the
// ‘csrf_exclude_uris’ config parameter:
// config.php
// Below setting will fix 403 forbidden issue permanently
$config['csrf_exclude_uris'] = array(
'admin/users/view/fetch_user', // use ajax URL here
);
$('#zero-config').DataTable({
"processing" : true,
"serverSide" : true,
"order" : [],
"searching" : true,
"ordering": false,
"ajax" : {
url:"<?php echo site_url(); ?>admin/users/view/fetch_user",
type:"POST",
data: {
},
},
});

Why it shows 403(forbidden) when making an ajax request?

I've made an ajax call with this:
$('.start-rate-fixed').on('click', function(e){
e.preventDefault();
var videoRate = $('.start-rate input[name="rating"]:checked').val(),
productId = parseInt($('.popover-content').prop('id'));
$.ajax({
url : ROOT + 'products/rate_video',
type : 'POST',
data : {
'data[Product][id]' : productId,
'data[Product][success_rate]' : videoRate
}
}).done(function(res){
var data = $.parseJSON(res);
alert(data);
});
});
Where I defined ROOT as the webroot of my cakephp project in my default.ctp with this:
<script type="text/javascript">
var ROOT = '<?php echo $this->Html->url('/');?>';
</script>
and trying to retrieve data from a function "rate_video" defined in my products controller but I get this error. Also I've tried a simple ajax for a test function but it showed me the same issue.
Controller Code
public function rate_video(){
$this->autoRender = false;
if($this->request->is('post') && $this->request->is('ajax')){
$success_rate = $this->request->data['Product']['success_rate'];
$this->Product->id = $this->request->data['Product']['id'];
if($this->Product->saveField('success_rate', $success_rate)){
echo json_encode('Successfully Rated');
} else {
echo json_encode('Error!!');
}
}
}
Please add dataType and a forward slash (/) at the end of your request URL
$.ajax({
url : ROOT + 'products/rate_video/',
type : 'POST',
data : {
'data[Product][id]' : productId,
'data[Product][success_rate]' : videoRate
},
dataType: 'json',
}).done(function(res){
I just had the same problem and solved it by putting the URL within AJAX call to a URL that I know works. Then try accessing the URL that you are trying to invoke via AJAX directly within the web browser - most likely you are accessing a controller that does not have a view file created. To fix this you have to ensure that the controller method being accessed does not have a view to be rendered - set $this->render(null)
If you have incorrect url then
url: '<?php echo Router::url(array('controller' => 'Controllername', 'action' => 'actionname')); ?>'
this above url provide ajax to url from root to your action.
And other cause for 403 is your auth function, if your using auth in your controller then make your ajax function allow like
$this->Auth->allow('Your ajax function name here');
Your script placed at localhost/dev.popover/products/rate_video but ajax ROOT is / - that mean localhost/ and ajax sent request to
'localhost/products/rate_video'
Right solution is
<script type="text/javascript">
var ROOT = '<?php echo $this->Html->url('/dev.popover/');?>';
</script>

Categories