How do I check if the request is made via AJAX in CodeIgniter?

前端 未结 7 1999
余生分开走
余生分开走 2020-11-28 08:29

How do I check if the request is an AJAX? I am using CodeIgniter. I have a link that when it clicked, it\'ll open the pop-up dialog window this is done through ajax it reque

相关标签:
7条回答
  • 2020-11-28 09:03

    Codeigniter has inbuilt function to check if the request is made using Ajax call.

    You can use the following way to validate if a controller/segment is called using Ajax or not.

    <?php
    Class Only_ajax extends CI_controller{
    
       function validate_user()
      {
         /*
          * Check if URL only_ajax/validate_url is called from ajax
          * if not display not found error to user.
          *
          **/
    
         if(!$this->input->is_ajax_request()){
           show_404();
         }
    
      }
    
    }
    

    You can use many other checks as well using input class. Few of them are

    • $this->input->get_request_header();
    • $this->input->is_cli_request()
    • $this->input->ip_address()

    You can view complete list of available methods at Official documentation

    0 讨论(0)
  • 2020-11-28 09:08

    I think you are basically looking to protect your ajax api's from being accessed directly by the users. You want users to be able to access ajax api's when invoked by your own code (javascript etc) but users should be denied access if they try to directly hit the api.

    If you are still looking for a perfect solution (HTTP_X_REQUESTED_WITH is not always reliable, since your library might not support this. Even it might get stripped off by proxies if user is behind one) try to use crumbs to protect your ajax api's. Crumbs are used for flow validation, which make sure that users access the api's via a pre-defined/pre-decided flow and not directly.

    0 讨论(0)
  • 2020-11-28 09:09

    In Codeigniter we can use

    if(!$this->input->is_ajax_request()){ // check if request comes from an ajax
        redirect(site_url('home'),'refresh'); // if the request is not coming from an ajax redirect to home controller.
    }
    
    0 讨论(0)
  • 2020-11-28 09:12

    If you are using a library that sends the X-Requested-With header, then you can do...

    if (strtolower(filter_input(INPUT_SERVER, 'HTTP_X_REQUESTED_WITH')) === 'xmlhttprequest') {
       // I'm AJAX!
    }
    
    0 讨论(0)
  • 2020-11-28 09:17

    Instead of detecting whether your request was an ajax request or not(Which can be any HTTP verb - GET/POST/HEAD) you may wanna try and add/modify routes to your routes.php for specifically handling these scenarios.

    0 讨论(0)
  • 2020-11-28 09:17

    In Yii you simply check

        if (Yii::app()->request->isAjaxRequest)
    

    If you use jQuery or other major javascript library it works. If you do custom requests, don't forget ot set X-Requested-With HTTP header to XMLHttpRequest.

    0 讨论(0)
提交回复
热议问题