Why is my AJAX .post not working in Codeigniter? - php

So this is my first Codeigniter project, and I'm about to commit seppuku.
Here is the situation:
I have a gallery of pictures. When the user hovers over one of them a side div populates with more info called in by AJAX.
I just can't get it to work. I keep getting this in Dev Tools>Network>XHR :
Not Found
The requested URL /ajax/getMoreInfo was not found on this server.
Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.
What am I doing wrong? and if anyone wants to drop some 'best practices', I'm all ears. Specifically.. I have seen other examples where ajax parameters are passed via the URL sent with $.post (ajax/getMoreInfo/ID) and not as a variable as I do here. Am I completely wrong? (Even though I dont think that is the cause of my 404).
Here is my JS function called on hover
function showDataWindow(){
var thisClass = $(this).attr('class');
var thisIDpos = thisClass.indexOf("id-")+3;
var thisID = thisClass.substr(thisIDpos, 3);
/// alert(thisID) <- alerts correctly
$.post('ajax/getMoreInfo',
{ ID: thisID },
function(data) {
.. do stuff with data
I have a controller named ajax.php in /controllers
<?php
class Ajax extends CI_Controller {
function __construct() {
parent::__construct();
}
public function getMoreInfo()
{
$ID = $this->input->post('ID');
$this->load->model('Artist_model','',TRUE);
$more_info = $this->Artist_model->get_more_info($ID);
echo json_encode($more_info);
}
}
And my model in /models...
<?php
class Artist_model extends CI_Model {
function __construct()
{
parent::__construct();
}
public function get_more_info($ID)
{
$query = $this->db->query('SELECT * FROM `NOIRusers` WHERE `UID` = `$ID`');
if ($query->num_rows() > 0)
{
foreach ($query->result() as $result)
{
$moreInfo['memberID'] =$result->UID;
$moreInfo['firstName'] =$result->UFname;
$moreInfo['lastName'] =$result->ULname;
$moreInfo['large_image_location'] =$result->large_image_location;
..more of these..
}
}
}
Thanks for any help!

I think its an htaccess issue. Try using the following content in your .htaccess file.
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?$1 [L]

Have you added it to the routes.php?
http://codeigniter.com/user_guide/general/routing.html
You will need to add it in here so CI knows what to do with 'ajax'.

please try this following query if you can pass the id properly.
SELECT * FROM NOIRusers WHERE UID = '".$ID."'";
normally codeigniter use like
$this->db->select('*');
$this->db->from('NOIRusers');
$this->db->where('UID',$ID);

Related

page redirect issue codeigniter

I am unable to redirect to page using the redirect() in codeigniter. Also the same problem if I try to use location.href within view. It just redirects me to the page without the css and js includes
mY CONFIG
$config['base_url'] = 'http://localhost/tsb/';
$config['index_page'] = '';
$config['uri_protocol'] = 'REQUEST_URI'; //I have switched the 3 protocols too
HTACCESS
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>
BOOK CONTROLLER
public function psg_sel()
{
$book_name = $this->input->post('book_name');
$book_id = $this->cj_model->get_book_id($book_name);
$ch_id = $this->input->post('chapter_id');
$cj_mask = $this->input->post('cj_mask');
if($cj_mask == ''){
$psg_sel = $this->cj_model->psg_sel($book_id, $ch_id);
if($psg_sel === true){
redirect(base_url() . 'passage/', 'refresh');
}
}
}
PASSAGE CONTROLLER
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Passage extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->database();
}
public function index()
{
$data['page_name'] = 'passage';
$this->load->view('pages/index', $data);
}
}
Please help I dont know whats going wrong. I can access http://localhost/tsb/passage/ directly from address bar but none of these will work properly location.href="passage/";or redirect(base_url() . 'passage/', 'refresh'); This is how it displays
At controller try this code. First load url helper then try..
The redirect statement in code igniter sends the user to the specified web page using a redirect header statement.This statement resides in the URL helper which is loaded in the following way:
$this->load->helper('url'); //loads url helper
Controller:
public function psg_sel()
{
$this->load->helper('url'); //loads url helper
$book_name = $this->input->post('book_name');
$book_id = $this->cj_model->get_book_id($book_name);
$ch_id = $this->input->post('chapter_id');
$cj_mask = $this->input->post('cj_mask');
if($cj_mask == ''){
$psg_sel = $this->cj_model->psg_sel($book_id, $ch_id);
if($psg_sel === true){
redirect(base_url('passage'), 'refresh');
}
}
}

Error 404 when routing

I'm trying to do my site like this tutorial http://www.codeigniter.com/user_guide/tutorial/static_pages.html
but have some problem with routing. I have page "createBook" for default and when I call localhost it's work! But when I do like localhost/createBook I have Error 404. What I'm doing wrong?
In my controller:
public function view($page = 'createBook')
{
if ( ! file_exists(APPPATH.'views/'.$page.'.php'))
{
// Whoops, we don't have a page for that!
show_404();
}
$this->load->view($page);
}
routes.php file
$route['default_controller'] = 'Books/view';
$route['(:any)'] = 'Books/view/$1';
And I have view files in my views folder named Success and createBook
I don't really get your question but it seems to me that you are trying to call a controller named createBook from the url, but in your function it shows that if there is no views/createBook.php than show 404, maybe its why you get a 404, because your calling a controller as a view, i think your function should be like this :
public function view($page = 'createBook')
{
if ( ! file_exists(APPPATH.'controllers/' . $page . '.php'))
{
// Whoops, we don't have a page for that!
$this->output->set_status_header('404');
show_404();
}
$this->load->view($page);
}
If you want your url to look something like this :
example.com/view/book/3
Your controller should look like this :
class View extends CI_Controller
{
public function book($book_id)
{
//Search the database for records about a book with its id, and return the data
//and assign it to a variable(in this case $data) ex : $data["book-name"] = ...
//And on your view you can call these values using ex : echo $book-name
$this->load->view('books_view', $data);
}
}
And make sure your .htaccess file next to the index.php looks like something like this :
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php/$0 [PT,L]
Then go to your config, and change this line to :
$config['index_page'] = '';
Now you can access all of your controllers this way :
http://www.example.com/controller_name

Passing value through url

I am trying to send a url from view page to controller but it does not seem to work the way i am thinking.
View Page
Product
User
I want to get "tbl_product"
Controller admin
<?php
class Admin extends CI_Controller {
public function test() {
echo $this->uri->segment(4);
}
}
?>
but if the segment(4) is changed to segment(3), it shows up with displaying "product" in the screen
your controller function should have arguments for your url segments
for example:
public function test($product = 'product', $tbl = 'tbl_product') {
echo $tbl // contains the string tbl_product
}
Since you said your routes look like this:
$route['default_controller'] = "admin";
$route['404_override'] = ''
and your URL is like this:
<?= base_url() ?>admin/test/product/tbl_product
Then if your base_url() is localhost/my_app, your URL will be read as this:
http://localhost/my_app/admin/test/product/tbl_product
http://localhost/my_app/CONTROLLER/METHOD/PARAMETER/PARAMETER
So in your controller, you can do this:
class Admin extends CI_Controller {
public function test($product = NULL, $tbl_product = NULL) {
echo $product;
echo $tbl_product;
}
}
It's strange to use codeigniter for this purpose, because codeigniter uses as default the url format bellow.
"[base_url]/[controller]/[method]"
I think it will be better and more easy to just pass the values you want as get parameters and make some httaccess rules to make your url more readable for the user and robots. That said you can do that:
Product
<?php
class Admin extends CI_Controller {
public function test() {
echo $this->input->get('product');
//should output 'tbl_product'
}
}
?>
If you prefer to use uri instead u should route your uri's so it will be like.
In your routes file you probably I'll need something like this.
$route['product/(:any)'] = "Admin/test";
This way you will probably access the uri segments correctly.
Thank you so much for going through.
$this->uri->segment(4); // is now working :S
its not working properly after all I made changes to routes.php and came back to default again. I seriously have no idea what the reason behind not displaying the result before.

Unable to redirect to a new page - CodeIgniter

I have a login system that works, but on the redirect function it gives me the error The requested URL "http://localhost/musiclear/index.php/welcome" cannot be found or is not available. Please check the spelling or try again later.
This is where I am using it (login.php):
function validate_credentials() {
$this->load->model('membership_model');
$query = $this->membership_model->validate();
if ($query) { // if users credentials validated
$data = array('usernames' => $this->input->post('username'),
'is_logged_in' => true);
$this->session->set_userdata($data); //set session data
redirect('welcome', 'refresh'); //redirect to home page
} else { //incorrect username or password
$this->index();
}
}
This is where I am directing it to (welcome.php):
class Welcome extends CI_Controller {
public function index() {
$this->home();
}
public function home() {
$this->load->model('model_users');
$data['title'] = 'MVC Cool Title'; // $title
$data['page_header'] = 'Intro to MVC Design';
$data['firstnames'] = $this->model_users->getFirstNames();
// just stored the array of objects into $data['firstnames] it will be accessible in the views as $firstnames
$data['users'] = $this->model_users->getUsers();
$this->load->view('home_view', $data);
}
}
Im thinking it is something wrong with the path, or where its linking to but im not sure. This is my directory setup:
Can someone please tell me whats wrong and how I can make it link to my page? Thanks so much
Have you created the .htaccess in your application folder?
Maybe this can work for your project:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /musiclear/index.php/$1 [L]
</IfModule>
<IfModule !mod_rewrite.c>
ErrorDocument 404 /musiclear/index.php
</IfModule>
You are welcome

SEO url gives 404-error in CodeIgniter

I am pretty new to codeigniter. I do know php.
How can I accomplish to load the right view?
My url: /blog/this-is-my-title
I’ve told the controller something like
if end($this->uri->segment_array()) does exist in DB then load this data into some view.
I am getting an 404-error everytime I access /blog/whatever
What am i seeing wrong?
unless you're using routing, the url /blog/this-is-my-title will always 404 because CI is looking for a method called this-is-my-title, which of course doesn't exist.
A quick fix is to put your post display code in to another function and edit the URLs to access posts from say: /blog/view/the-post-title
A route like:
$route['blog/(:any)'] = "blog/view/$1";
may also achieve what you want, if you want the URI to stay as just `/blog/this-is-my-title'
The may be more possibilities:
The most common - mod_rewrite is not active
.htaccess is not configured correctly (if u didn't edited it try /blog/index.php/whatever)
The controller does not exist or is placed in the wrong folder
Suggestion: if you only need to change data use another view in the same controller
if (something)
{
$this->load->view('whatever');
}
else
{
$this->load->view('somethingelse');
}
If none of those works post a sample of code and configuration of .htaccess and I'll take a look.
The best way to solve this problem is to remap the controller. That way, you can still use the same controller to do other things too.
No routing required!
enter code here
<?php
class Blog extends Controller {
function __construct()
{
parent::__construct();
}
public function _remap($method, $params = array())
{
if (method_exists($this, $method))
{
$this->$method();
}
else
{
$this->show_post();
}
}
function index()
{
// show blog front page
echo 'blog';
}
function edit()
{
// edit blog entry
}
function category()
{
// list entries for this category
}
function show_post()
{
$url_title = $this->uri->segment(2);
// get the post by the url_title
if(NO RESULTS)
{
show_404();
}
else
{
// show post
}
}
}
?>

Categories