I'm writing a PHP application using codeigniter framework. I'm trying to add a tool to download the data in the page as a .csv format file. I have the code to the server side, but I'm having trouble handling the URL mapping for the "Download" Controller.
in /controllers/ I have a controller called "Download", which is has a function called 'exportCSV', which receives a json object that is decoded and used to create the file. So, I'm trying to send a JavaScript array through 'post' to that method, but I'm having trouble handling the URL mapping.
here is my javascript call ...
function download(){
$.post('index.php/download/exportCSV', {input : dataForDownload.toString()},
function(answer){
alert(answer);
}
);
}
POST to index.php/download/exportcsv. CI doesn't much like Mixed Case controllers.
If you have a download controller, it should look like this:
class Download extends CI_Controller
{
function _construct()
{
parent::_construct();
}
function exportcsv()
{
if($this->input->post())
{
// Something was POSTed, continue
// process input
} else {
// Catch error if no POST
}
}
}
If you're getting a 404, your application might not be set up correctly. Check routes.php and your base_url.
I also recommend the CodeIgniter user guide. It's full of good information:
http://codeigniter.com/user_guide/overview/appflow.html
http://codeigniter.com/user_guide/overview/mvc.html
Related
I am trying to integrate RESTful services to my Codeigniter application. I am using this library https://github.com/chriskacerguis/codeigniter-restserver and the tutorial from https://code.tutsplus.com/tutorials/working-with-restful-services-in-codeigniter--net-8814.
However, I am a little confused about how to implement routing. The tutorial mentions using the full url but I'd like to do something like:
My Controller
class AdminLogin_WS extends REST_Controller {
public function __construct() {
parent::__construct();
$this->load->model('AccountModel');
}
public function login_get(){
$this->response(json_encode(null));
}
public function login_post(){
$username = $this->post('username');
$this->response(json_encode($username));
}
}
My routes
$route['AdminLogin_WS/Login']['post']= 'AdminLogin_WS/login_post'; <= this will trigger an unknown method error
$route['AdminLogin_WS/Login']= 'AdminLogin_WS/login'; <= this will call the get function
REST Request
public function ws_login(){
$this->curl->create('https://url.com/AdminLogin_WS/Login');
$this->curl->http_login('login','password');
$this->curl->post(array(
'username' => 'auser'
));
$result = $this->curl->execute();
var_dump(json_decode($result));
}
How can I specify what function is a post or get?
You can specify is a function is post or get by using _post() and _get() respectively.
For your routing, I think you are routing wrongly. There should be a difference between the main route and the alternate route. You should have something like
$route['method/param1'] = 'controller/method/param1';
Updated with information from chat
Using login_get() and login_post() and then making the POST request to AdminLogin_WS/login was the correct thing to do, and the login_post() was getting called, there was just some confusion because the POST was returning the same response as the GET using the code that the poster was using.
Original answer
I would post this as a comment but don't have the rep to do so.
What do you mean by "It only works if I create a controller function called login_get()"? That sounds to me like you're sending in a GET rather than a POST to your route. Can you give some information on how you're testing to see if you can POST and get to your login_post()? Have you tried downloading a tool like Postman (https://www.getpostman.com/) and sending in a POST to help eliminate the possibility that you're not sending in the POST correctly?
I have an AJAX featured page with dynamic components. I was wondering about how to handle an ajax call in MVC.
The first idea I had was to create a new controller for ajax calls without rendering views and check in the routing for an ajax request like this
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
call_user_func_array(array("ajax", $this->url_action), null);
}
I would let the location of AJAX handling code depend on its context. If it is handling the same kind of content as another controller that returns a full view, just make an "ajax method" in that controller, that responds with for instance a JSON header, the contents you want to send to the browser and exits. Not really a need for a dedicated AJAX controller, just like you don't have a separate GET controller or POST controller.
EDIT: (an example)
class BookController
{
public function getBookDetail($id)
{
// Go fetch a book from the DB.
// Assemble your full fledged view
// Send it to the browser
}
public function ajaxBookDetail($id)
{
// Go fetch a book from the DB.
header('Content-Type: application/json');
echo json_encode($someBookData);
exit;
}
}
You can then tell your router to use the ajax-prefixed method instead of the get-prefixed one, if you detect xmlhttprequest in the SERVER headers.
I am working in codeigniter and Iam looking to make my own custom validation class using "Validation_form" library and my custom rule where I will place my own validation rules and use that from everywhere in my project, but this seems impossible, I tried in couples ways to handle this but nothing.
Codeigniter kindle force me to make my callback methods in my controller but I need them in my library or "method" or wherever else!!!
My question is, can I build an specific library where I'll place my validation rules and other functions I need to handle that?
you could create a new library in application/libriries and name the file MY_Form_validation
What you are doing here is extending the form_validation class so that you will not need to mess with the core files.
The MY_ is what is set on your config, be sure to check it if you changed yours.
sample MY_Form_validation.php
class MY_Form_validation Extends CI_Form_validation
{
//this is mandatory for this class
//do not forget this or it will not work
public function __construct($rules = array(){
parent::__construct($rules);
$this->CI->lang->load('MY_form_validation');
}
public function method1($str){
return $str == '' ? FALSE : TRUE;
}
pulic function method2($str)
{
//if you want a validation from database
//you can load it here
// or check the `form_validation` file on `system/libraries/form_validation`
}
public function check_something_with_post($tr)
{
return $this->CI->input->post('some_post') == FALSE ? FALSE : TRUE;
}
}
Basically, when you call a rule sample method1|method2 the value of your post field will be the parameter of the method. if you want to check other post you can do it by using $this->CI->input->post('name of the post');
when you want to pass a parameter just look at the form validation is_unique or unique code on system/libraries/form_validation you will have an idea.
To create a error message that goes with it go to application/language/english/MY_Form_validation_lang
Sample MY_form_validation_lang.php
$lang['method1'] = "error error error.";
$lang['method2'] = "this is an error message.";
if english does not exist on your application/language just create it.
check more atCreating libraries
NOTE:
On some linux or debian server you may want to change the file name from MY_Form_validation to
MY_form_validation note the small f on the word form.
I'm working on a project that allows external users(coming from another source than just my server) to make a GET request to a page on my server, which will then return some JSON encoded data.
For example, say the data (not using Cake, just standard PHP) would be sent to
wwww.example.com/handlerequest.php
I'd just have something like
if(isset($_GET['userRequest'])){
//do some stuff
echo $json_encoded_stuff;
}
With CakePHP I'd just post the data to something like
www.example.com/HandleRequest
However, I do not want/need a view for this because there is nothing to see. This page is purely for data exchange. Considering this, is there anything special I have to do so that Cake doesn't throw an error because it's expecting a corresponding view? Is this even possible?
It is easy to disable both the layout and view in CakePHP by putting the following line in your controller action:
$this->autoRender = false;
If you want to disable just the layout, use the following line in your controller action:
$this->layout = false;
And if you only want to disable the view for this action, use the following line in your controller:
$this->render(false);
Note that using $this->layout = false; and $this->render(false); together in your controller action will give you the same results as $this->autoRender = false;
I have a form that submits to the submit_ajax method when submitted via AJAX. Now, when I receive it as an AJAX request, I want to return a JSON object.
In this case, I have two options. What would be considered the right way to do it, following the MVC pattern?
Option 1
Echo it from the controller
class StackOverflow extends CI_Controller
{
public function submit_ajax()
{
$response['status'] = true;
$response['message'] = 'foobar';
echo json_encode($response);
}
}
Option 2 Set up a view that receives data from the controller and echoes it.
class StackOverflow extends CI_Controller
{
public function submit_ajax()
{
$response['status'] = true;
$response['message'] = 'foobar';
$data['response'] = $response;
$this->load->view('return_json',$data);
}
}
//return_json view
echo json_encode($response);
The great thing about CodeIgniter is that in most cases it's up to yourself to decide which one you're more comfortable with.
If you (and your colleges) prefer to echo through the Controller, go for it!
I personally echo ajax replies through the Controller cause it's easy and you have all of your simple scripts gathered, instead of having to open a view file to confirm an obivous json_encode().
The only time I'd see it to be logical to use view in this case is if you have 2 view files that echo's json and XML for instance. Then it can be nice to pass the same value to these views and get different outcome.
The correct way according to the MVC pattern is to display data in the View. The Controller should not display data at any case.
MVC is often seen in web applications where the view is the HTML or
XHTML generated by the application. The controller receives GET or
POST input and decides what to do with it...
source: http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller
Usually when you have to show something on success in ajax funnction you need flags means some messages. And according to those messages you display or play in success function . Now there is no need to create an extra view. a simple echo json_encode() in controller is enough. Which is easy to manipulate.