How to Pass a Number With Forward Slash "/" to Codeigniter Controller Using Ajax

Display id using ajax to controller

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
enter image description here

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

Unsuccessful AJAX call to controller using CodeIgniter

You're facing an error probably because the method expects an argument you're not providing (and the router can't work the call right). Try this 2 things:

1) crate an url using the built-in functions (to avoid problems with that):

url: "<?php echo site_url('lotto/get_results');?>"

2) Since the method looks like should receive a POST variable, and not a GET one, you need to fetch it the right way:

public function get_results() {
$numOfDraws = $this->input->post('numOfDraws');
//do something with $numOfDraws here
echo $numOfDraws; // just to check the value is being passed
}

Passing an argument to the method works if the variable comes from an HTTP GET request, which is not your case. If that's your intention, instead, you need to remove the "POST" type in the AJAX call and provide a value while building the AJAX url. Somethng like

url: "<?php echo site_url('lotto/get_results');?>/"+numOfDraws;

In this case, your method would be get_result($draws) , with the parameter

CodeIgniter routing problem. (appends ajax route to existing url)

It is because your Javascript is using the current directory as the base, and appending the AJAX URL to it. Because you are (to the client-side at least) in the companies directory, it appends your URL onto this.

The solution, if your Javascript is inline, is to just use the base_url() PHP function wihtin the code ...

var url = '<?= base_url(); ?>test_ajax/'

If your Javascript is not inline, you can declare a global variable at the top of your HTML document using the PHP function...

var BASE_URL = '<?= base_url(); ?>'

And use it everywhere else in your Javascript ...

var url = BASE_URL + 'test_ajax/'

Alternatively, you could just hardcode your base URL, but that could get real messy real quick.

GET parameters in the URL with CodeIgniter

When I first started working with CodeIgniter, not using GET really threw me off as well. But then I realized that you can simulate GET parameters by manipulating the URI using the built-in URI Class. It's fantastic and it makes your URLs look better.

Or if you really need GETs working you can put this into your controller:

parse_str($_SERVER['QUERY_STRING'], $_GET); 

Which will put the variables back into the GET array.

Codeigniter: error 400 where sending file to server using Ajax

it's a security issue ( CSRF Proctection in Codeigniter ).
We should add csrf_token to data before sending it:

form_data.append('csrf_token_name', 'token');

or disable CSRF Proctection from config file.

Laravel: Get base URL

You can use the URL facade which lets you do calls to the URL generator

So you can do:

URL::to('/');

You can also use the application container:

$app->make('url')->to('/');
$app['url']->to('/');
App::make('url')->to('/');

Or inject the UrlGenerator:

<?php
namespace Vendor\Your\Class\Namespace;

use Illuminate\Routing\UrlGenerator;

class Classname
{
protected $url;

public function __construct(UrlGenerator $url)
{
$this->url = $url;
}

public function methodName()
{
$this->url->to('/');
}
}


Related Topics



Leave a reply



Submit