ci Method for detecting whether ajax or page post submits data

  • 2021-07-26 07:10:13
  • OfStack

This article illustrates how ci detects whether ajax or page post submits data. Share it for your reference. The specific implementation method is as follows:

1. Issues:

Because the project requires that we want to know whether the submitted data source is the data submitted by ajax or the data submitted by post of the page, so as to process it at different levels.

2. Solution:

The solution in php is as follows:
If it is an ajax request, the value of the following expression is true

$_SERVER["HTTP_X_REQUESTED_WITH"]=="XMLHttpRequest"

Is an environment variable for PHP.

Treatment in ci:

define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
define("IS_POST", strtolower($_SERVER['REQUEST_METHOD']) == 'post');

Remember that when using THINKPHP, there are two built-in constants IS_AJAX and IS_POST. If you want to use it in ci for a long time, it seems that you can't find it, so you will automatically start to have enough food and clothing
Add the above two lines of code to the config/constants. php configuration file of the project, so that you can call it directly in all methods
For example:

if(IS_POST){
 ...
}
if(IS_AJAX){
...
}

I hope this article is helpful to everyone's CI framework programming.


Related articles: