简体   繁体   中英

Using $.post, $.ajax or AJAX properly in CodeIgniter to call a PHP script

I'm not so much of a framework fan but I have been made to use it because I am working on a project that others may edit later.

I am using the CodeIgniter framework (I'm kinda new on it).

I am using jquery $.post(url, function() {}) to asynchronously call a login parser that is in the root directory under a folder called php-parser I realized this folder does not make use of any of the CodeIgniter's ready made class. I decided to move the folder php-parser into application/libraries but when I tried to use jQuery to call it referencing the full path /application/libraries/php-parser/the-script.php , it return a 403 forbidden error

What do you think I can do? Some people said I could make the script a controller but here is what is going on, It's a popup modal login page. From any page if you click the login / register button, the modal pops up, how can I make a controller and a model for that (if I'm to follow that procedure).

Added: I put the modal content at the end of the footer which is included on all pages, how do I get to create a controller for that kind of modal? Any help!

When dealing with MVC (at least the way you are using it) you have three parts:

  • The Model - in this case this is the code which interacts with your database.
  • The View - the code which formats the data you are sending back to the browser
  • The Controller - the code which connects the two together and might have some business logic in it.

You also have some routing code which maps a URL onto the right controller for that URL.


Browsers (and other clients) only interact with web servers through URLs.

So you absolutely need to have a Controller set up to handle the request from the browser.


If you are doing this the quick and dirty way, then your controller will just get the username and password from the POST request, check it against the database with the model, and then squirt either "Success!" or "Fail!" into the view (which is probably best written as something that returns JSON formatted back to the browser).


If you are being sensibly robust about this then the view will have logic something along the lines of:

Does the browser explicitly include JSON in the accept header?

If so, send back a bit of JSON saying "success" or "failure" (or true / false, or whatever makes sense for you).

Does it not? Then either return a "Sorry, you failed to login!" HTML document or a redirect back to the page they came from (so it will reload in the logged in state).

That way, if the JavaScript fails for any reason , the plain HTML form which was progressively enhanced with the Ajax JavaScript will still function. (NB: You have to write it that way!).

jQuery will automatically include a JSON friendly Accept header if you say dataType: "json" in the Ajax options.

Yes, you will need to put your file inside the libraries folder(if the class is separate from codeigniter or is shared among many controllers, if not a Model would suffice), then create a controller for it.

class Ajax_Controller extends CI_Controller
{

    public $statusCode = 200;

    public $response = array();

    public function __construct()
    { 
       parent::__construct();

       if(!$this->is_ajax_request()){
          return; // direct access not allowed
       }

       $this->response = array(
           'error' => false,
           'text'  => "",
           'fields' => array()
       );
    }

    public function sendResponse()
    {
        return $this->output
                    ->set_status_header($this->statusCode)
                    ->set_content_type('application/json')
                    ->set_output(json_encode($this->response));
    }
}
class Auth extends Ajax_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->library('php-parser/script', 'authentication');
    }

    public function login()
    {

        if(!$this->form_validation->run()){
            $this->response = array(
               'error' => true,
               'text'  => "The form has some errors",
               'fields' => array(
                   'username' => form_error('username'),
                   'password' => form_error('password')
               )
           );
           return $this->sendResponse();
        }

        $username= $this->input->post('username');
        $password= $this->input->post('password');

        if(!$this->authentication->login($username, $password)){
            $this->response = array(
                'error' => true,
                'text'  => "incorrect username/password combination",
                'fields' => array() 
            );
            $this->statusCode = 401;
            return $this->sendResponse();
        }


    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM