Calling CodeIgniter controller method returns 404 - codeigniter

First attempt with CI, and get a "page not found" error when use Ajax to call method. Have double-checked the names, and just lost at sea now.
[page_a.php]
<script>
function f1() {
$.ajax({
type: 'POST',
url: '<?= site_url("controller_a/method_a") ?>',
error: function (jqXHR, exception) {
var msg = '';
if (jqXHR.status == 0 ) msg = 'Not connected, verify network [000]';
else if (jqXHR.status == 404 ) msg = 'Requested page not found [404]';
else if (jqXHR.status == 500 ) msg = 'Internal server error [500]';
else if (exception == 'parsererror') msg = 'Requested JSON parse failed';
else if (exception == 'timeout' ) msg = 'Time out error';
else if (exception == 'abort' ) msg = 'Ajax request aborted';
else msg = jqXHR.responseText;
alert(msg);
}});}
</script>
[controller_a.php]
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class controller_a extends MY_Controller {
public function method_a() {
echo '<script>alert(":-)");</script>';
}}

url: "<?php echo site_url('Controller/method')?>",
Try this keep the Controller's first letter capital and echo the site url.

Please check your routes.php file. probably there is another redirect in this file.
and

[page_a.php]
<script>
function f1() {
$.ajax({
type: 'POST',
url: '<?= site_url("index.php/Controller_a/Method_a") ?>'
});}
</script>
[Controller_a.php]
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Controller_a extends CI_Controller {
public function Method_a() {
echo '<script>alert(":-)");</script>';
}}
Tried the uppercase, extend CI_Controller, and index.php, but no luck yet.
I noticed that if I use
<?= site_url("Controller_a/Method_a") ?>
in the html, so that it's called when the page loaded/rendered, then the method is found and called, but just not found when dynamically called with Ajax/JS after the page is loaded.
In the console the address is
www.example.com/Controller_a/Method_a
The actual address is
www.example.com/web/content/application/controllers/Controller_a.php

Related

Admin ajax in wordpress is not working

I am using admin ajax but it is not working. Kindly, help me to find out the problem. Here is jquery code
jQuery(document).ready(function($) {
jQuery('#newPostsForm').submit(ajaxSubmit);
function ajaxSubmit(){
var newPostsForm = jQuery(this).serialize();
jQuery.ajax({
type:"POST",
url: "<?php echo admin_url('admin-ajax.php'); ?>",
data: newPostsForm,
success:function(data){
jQuery("#feedback").html(data);
}
});
return false;
}
}):
If I alert the var "newPostsForm" , it shown the posted values.but it is now proceeding to ajax. Here is the from I am using
<form type="post" action="" id="newPostsForm">
<input type="hidden" name="action" value="addPosts"/>
<!-- input fields -->
</form>
An here is the WordPress function I am using. this function is another file. HTML and javascript are in same file
function addPosts(){
echo "<pre>";
print_r($_POST);
die();
}
add_action('wp_ajax_addPosts', 'addPosts');
add_action('wp_ajax_nopriv_addPosts', 'addPosts'); // not really needed
Check to see if the script is getting processed by PHP before it is sent to the client. Change the code to something similar to this:
jQuery(document).ready(function($) {
jQuery('#newPostsForm').submit(ajaxSubmit);
function ajaxSubmit() {
var newPostsForm = jQuery(this).serialize();
var url = "<?php echo admin_url('admin-ajax.php'); ?>";
alert("Submitting to URL: " + url);
jQuery.ajax({
type:"POST",
url: url,
data: newPostsForm,
success:function(data){
jQuery("#feedback").html(data);
},
error: function (xhr, status, err) {
alert("Got status " + status + " and error: " + err);
}
});
return false;
}
});
If you get an actual URL like https://mysite.example.org then check that the URL goes to a valid location. If you get <?php echo admin_url('admin-ajax.php'); ?> then your code is not getting processed by PHP, and the AJAX call will fail because you are not using a valid URL.
The problem seems that the AJAX URL is not accessible in JS code. If the JS code written into a PHP page then only the code will work. Because the PHP code cant be executed into the JS files.
NOW the solution is to localized the JS file. Please follow the code.
wp_localize_script( 'handle', 'settings', array('ajaxurl' => admin_url( 'admin-ajax.php' )));
Write the above code just under where you have enqueued your js file.
NOW in JS file :
jQuery.ajax({
type:"POST",
**url: settings.ajaxurl,**
data: newPostsForm,
success:function(data){
jQuery("#feedback").html(data);
}
});
Hope it will work at your choice.

How to call controller from another url with post data?

I have a problem with my project using codeigniter.
I want to run some controller from another url(without my project) with post data.
I'm using codeigniter framework?
so have any way to do this?
Please help me resolution this problem...
All I can think of is using ajax , but this is not recommended to use javascript as a part of the controller
in controller A
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class controllerA extends CI_Controller {
function __construct()
{
// you can put the ajax call here if you want it to run each time you call this controller
}
public function ajaxcall()
{
// make sure you didn't call jquery before so you won't have conflicting scripts
echo '<script src="https://code.jquery.com/jquery-1.11.3.min.js"> </script>';
// now we use ajax to post to the controller B
echo
'<script>
var target_url = "http://www.example.com/projectB/controllerB"
var Data = {user_id:542,name:"Baci"};
$.ajax(
{
url : target_url,
type: "POST",
data : Data,
success: function(data)
{
alert("all right request was sent via Ajax ");
},
error: function(jqXHR, textStatus, errorThrown)
{
alert("request failed ! ");
}
});
</script>
' ;
// continue your code on your controller while the ajax call is being sent
}
}

Ajax request to override controller in prestashop 1.6

outside the conventional methods of ajax requests from a prestashop module, I would like to use a ajax method from product.js and retrieve data from an override controller.
my function in product.js :
function attrReference(ref){
$.ajax({
url: baseUri,
async: true,
cache: false,
type:'GET',
dataType : "json",
headers: { "cache-control": "no-cache" },
data: {
controller :'product',
action :'attrReference',
token : token,
ajax: 1,
ref : ref
},
success: function(data){
}
});
}
My override controller product :
class ProductController extends ProductControllerCore{
public function displayAjaxAttrReference(){
echo '<pre style="background:yellow">';
print_r($_GET);
echo '</pre>';
exit;
}
}
From the documentation, i use displayAjax to recover data, unless this is not the right method, I tried many attempts but none are correct.
Do you have any idea?
If you need to retrieve data, or little piece of html i suggest to avoid the displayAjax function since it's called only at the end of the controller routine, and thus you will get everything processed (retrieving of template, database query and so on).
normally the controller function are called with the following list:
init();
setMedia();
// postProcess handles ajaxProcess
postProcess();
initHeader();
initContent();
initFooter();
displayAjax() || display();
as you can see displayAjax should be avoided if you don't want to retrieve the whole page/a template the require all the information of the product page.
To correctly route your request you should override also the postProcess function of your product controller such that:
public function postProcess(){
if(Tools::isSubmit('action') && Tools::getValue('action') == 'attrReference')
$this->AjaxGetReference();
parent::postProcess();
}
and then
public function AjaxGetReference(){
echo '<pre style="background:yellow">';
print_r($_GET);
echo '</pre>';
die();
}
Also, always remember to pass the id_product with your ajax function if you are interacting with the ProductController, else any action will fail becouse of the init function:
public function init()
{
parent::init();
if ($id_product = (int)Tools::getValue('id_product'))
$this->product = new Product($id_product, true, $this->context->language->id, $this->context->shop->id);
if (!Validate::isLoadedObject($this->product))
{
header('HTTP/1.1 404 Not Found');
header('Status: 404 Not Found');
$this->errors[] = Tools::displayError('Product not found');
}
}

Wordpress wp_ajax public url?

I would like to do an ajax request in my theme.
If I am login to the Back Office, the request does, but if I'm not logged in, the returns is null... What's the solution please ?
In my view :
$.ajax({
type: "POST",
url: 'http://www.mysite.com/wp-admin/admin-ajax.php',
data: $('#EventForm').serialize()+'&action=event_form',
success: function(response){
if(response == 1){
alert('ok');
} else {
alert('no ok');
}
});
In the functions.php (works only if I am log in back Office)
add_action('wp_ajax_event_form', 'ajax_event_form');
function ajax_event_form(){
global $wpdb;
...
echo true;
die;
}
From the Codex: wp_ajax_nopriv_(action) executes for users that are not logged in. So, if you want it to fire on the front-end for both visitors and logged-in users, you can do this:
add_action('wp_ajax_my_action', 'my_action_callback');
add_action('wp_ajax_nopriv_my_action', 'my_action_callback');
Create a plugin and add this:
<?php
/*
* Plugin Name:ajax
*/
function my_ajax_callback_function() {
echo "hiii";
print_r($_POST);
exit();
}
add_action( 'wp_ajax_my_action_name', 'my_ajax_callback_function' );
// If called from admin panel
add_action( 'wp_ajax_nopriv_my_action_name', 'my_ajax_callback_function' );
Create a js and add this:
(function($) {
$(document).ready(function(e) {
$.ajax({
url: "<?php echo admin_url('admin-ajax.php'); ?>",
type: 'POST',
data: {
action: "my_action_name","name":"hithin","age":"27"
},
success: function (data, textStatus, jqXHR) {
console.log(data);
}
});
}
})(jQuery);
The ajax request in WordPress works by classifying user in two categories
1) User with login privilege.
2) User without login privileges.
So if you are logged in(even as a subscriber) your ajax function will be triggered i.e.
add_action('wp_ajax_event_form', 'ajax_event_form');
this will call 'ajax_event_form' function.
To make this work for non-logged in users you will have to write this below your ajax action
add_action('wp_ajax_nopriv_event_form', 'ajax_event_form');
So your code will be like:
add_action('wp_ajax_event_form', 'ajax_event_form');
add_action('wp_ajax_nopriv_event_form', 'ajax_event_form');
function ajax_event_form(){
global $wpdb;
...
echo true;
die;
}

codeigniter ajax firebug shows 200 but display no results

I need a quick help. please help me to figure out the problem.
I have a client's project, that is in codeigniter framework.
my client need an auto complete on their site. i tried best to make it working. everything is ok i write the MVC according to the tutorial.
but my script returns nothing
my view for auto complete
<link rel="stylesheet" href="<?php echo $this->config->item('view_path');?>autocomplete/ui.theme.css" type="text/ css" media="all" />
<script src="<?php echo $this->config->item('view_path');?>autocomplete/1.4.3.jquery.min.js" type="text/javascript"></script>
<script src="<?php echo $this->config->item('view_path');?>autocomplete/1.8.6.jquery-ui.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(this).ready( function() {
$("#postcode").autocomplete({
minLength: 1,
source:
function(req, add){
$.ajax({
url: "<?php echo base_url(); ?>home/lookup",
dataType: 'json',
type: 'POST',
data: req,
success:
function(data){
if(data.response =="true"){
add(data.message);
}
},
});
},
select:
function(event, ui) {
$("#result").append(
"<li>"+ ui.item.value + "</li>"
);
},
});
});
</script>
My autocomplete controller is
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Autocomplete extends CI_Controller {
function index()
{
$this->load->view('autocomplete');
}
function lookup(){
// process posted form data (the requested items like province)
$keyword = $this->input->post('term');
$data['response'] = 'false'; //Set default response
$query = $this->MAutocomplete->lookup($keyword); //Search DB
if( ! empty($query) )
{
$data['response'] = 'true'; //Set response
$data['message'] = array(); //Create array
foreach( $query as $row )
{
$data['message'][] = array(
'id'=>$row->PC_POST_CODE,
'value' => $row->PC_TOWN.' '.$row->PC_POST_CODE,
''
); //Add a row to array
}
}
if('IS_AJAX')
{
echo json_encode($data); //echo json string if ajax request
}
else
{
$this->load->view('autocomplete/index',$data); //Load html view of search results
}
}
}
/* End of file autocomplete.php /
/ Location: ./application/controllers/autocomplete.php */
and Model is also same in example.
when i see in the console of fire bug i see this message but no result.
http://yaashinii.com/maxsurge/tyrechangr/index.php/home/lookup 200 OK 3.28s
site link is you can visit.
http://yaashinii.com/maxsurge/tyrechangr/
I also checks that when i use only a simpe ajax call then the same result as well. and even when i change the controller method to show only the result let say i change the
function lookup(){
echo 'waheed'; exit;
}
even then the same result
http://yaashinii.com/maxsurge/tyrechangr/index.php/home/lookup 200 OK 3.28s
Please help me it is a new kind of issue i didn't understand why it is happend.
I got the solution.
I am visiting this addrss http://www.yaashinii.com/maxsurge/tyrechangr/ but i have define base url in config file of codeigniter as http://yaashinii.com/maxsurge/tyrechangr/index.php/ therefor it becomes a cross domain. and ajax not allow a cross domain access. you can see that i am accessing with www and base url without www.

Resources