├── Ajax.php ├── LICENSE ├── ajax_test_view.php ├── encode_xml_helper.php ├── readme.md └── test.php /Ajax.php: -------------------------------------------------------------------------------- 1 | 9 | * @link https://github.com/ajillion/CodeIgniter-jQuery-Ajax 10 | */ 11 | class Ajax 12 | { 13 | function __construct() 14 | { 15 | $this->CI =& get_instance(); 16 | $this->CI->load->helper('url'); 17 | } 18 | 19 | /** 20 | * Output ajax 21 | * 22 | * @param mixed $data The data to encode and output. 23 | * @param string $output_type The output encode type. Options 'json', 'xml', 'html', or 'text'. Defaults to 'json'. 24 | * @param boolean $ajax_only Reject if this is not called by an xmlhttprequest. Defaults to TRUE. 25 | */ 26 | function output_ajax($data = NULL, $output_type = 'json', $require_ajax = TRUE) 27 | { 28 | $_output = NULL; 29 | 30 | if ($require_ajax === TRUE && ! IS_AJAX) 31 | { 32 | $this->CI->output->set_status_header('403'); 33 | $this->CI->output->set_header("Content-Type: text/plain"); 34 | $_output = 'Invalid Request Origin'; 35 | } 36 | else 37 | { 38 | // Encode data and set headers 39 | switch ($output_type) 40 | { 41 | case 'json': 42 | default: 43 | $_output = json_encode($data); 44 | $this->CI->output->set_header('Content-Type: application/json'); 45 | break; 46 | 47 | case 'xml': 48 | $this->CI->load->helper('encode_xml'); 49 | $_output = array_to_xml($data); 50 | $this->CI->output->set_header('Content-Type: application/xhtml+xml'); 51 | break; 52 | 53 | case 'text': 54 | $_output = $data; 55 | $this->CI->output->set_header('Content-Type: text/plain'); 56 | break; 57 | 58 | case 'html': 59 | $_output = $data; 60 | $this->CI->output->set_header('Content-Type: text/html'); 61 | break; 62 | } 63 | 64 | $this->CI->output->set_status_header('200'); 65 | $this->CI->output->set_header('Cache-Control: no-store, no-cache, must-revalidate'); 66 | $this->CI->output->set_header('Pragma: no-cache'); 67 | $this->CI->output->set_header('Access-Control-Allow-Origin: ' . base_url()); 68 | $this->CI->output->set_header('Content-Length: '. strlen($_output)); 69 | } 70 | 71 | $this->CI->output->set_output($_output); 72 | } 73 | 74 | function non_ajax($alert = TRUE) 75 | { 76 | if ( ! IS_AJAX && $alert === TRUE) 77 | { 78 | $this->CI =& get_instance(); 79 | 80 | $this->CI->output->set_status_header('403'); 81 | $this->CI->output->set_header("Content-Type: text/plain"); 82 | $this->CI->output->set_output('Invalid Request Origin'); 83 | } 84 | return ! IS_AJAX; 85 | } 86 | } 87 | 88 | /* End of file Ajax.php */ 89 | /* Location: ./app/libraries/Ajax.php */ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Josh Campbell 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /ajax_test_view.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | CI/jQ - Ajax Test 5 | 6 | 17 | 18 | 19 | 20 | 55 | 56 | 57 |
58 | 59 |

60 |
61 | 62 | -------------------------------------------------------------------------------- /encode_xml_helper.php: -------------------------------------------------------------------------------- 1 | 'something', 'data' => '1/1/1970') 16 | * 17 | * @access public 18 | * @param array $array The array to be converted to an XML string. 19 | * @param integer $level The XML version. Default 1.0 20 | * @return string 21 | */ 22 | function array_to_xml($array, $level = 1) 23 | { 24 | $xml = ''; 25 | if ($level==1) 26 | { 27 | $xml .= '' . "\n\n"; 28 | } 29 | foreach ($array as $key=>$value) 30 | { 31 | $key = strtolower($key); 32 | if (is_array($value)) 33 | { 34 | $multi_tags = false; 35 | foreach($value as $key2=>$value2) 36 | { 37 | if (is_array($value2)) 38 | { 39 | $xml .= str_repeat("\t",$level)."<$key>\n"; 40 | $xml .= array_to_xml($value2, $level+1); 41 | $xml .= str_repeat("\t",$level)."\n"; 42 | $multi_tags = true; 43 | } 44 | else 45 | { 46 | if (trim($value2)!='') 47 | { 48 | if (htmlspecialchars($value2)!=$value2) 49 | { 50 | $xml .= str_repeat("\t",$level) . "<$key>" . "\n"; 51 | } 52 | else 53 | { 54 | $xml .= str_repeat("\t",$level) . "<$key>$value2\n"; 55 | } 56 | } 57 | $multi_tags = true; 58 | } 59 | } 60 | if (!$multi_tags and count($value)>0) 61 | { 62 | $xml .= str_repeat("\t",$level)."<$key>\n"; 63 | $xml .= array_to_xml($value, $level+1); 64 | $xml .= str_repeat("\t",$level)."\n"; 65 | } 66 | } 67 | else 68 | { 69 | if (trim($value)!='') 70 | { 71 | if (htmlspecialchars($value)!=$value) 72 | { 73 | $xml .= str_repeat("\t",$level) . "<$key>" . "\n"; 74 | } 75 | else 76 | { 77 | $xml .= str_repeat("\t",$level) . "<$key>$value\n"; 78 | } 79 | } 80 | } 81 | } 82 | if ($level==1) 83 | { 84 | $xml .= "\n"; 85 | } 86 | return $xml; 87 | } 88 | 89 | /* End of file encode_xml_helper.php */ 90 | /* Location: ./app/helpers/encode_xml_helper.php */ -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 |

Setup

2 |

1. Place ajax.php in your application/libraries folder.

3 |

2. Add the following code to your application/config/constants.php file:

4 |
  5 | 
  6 | /*
  7 | |--------------------------------------------------------------------------
  8 | | Detect Ajax Requests
  9 | |--------------------------------------------------------------------------
 10 | |
 11 | | This constant is used to determine whether the request is an AJAX request, or a standard HTTP request.
 12 | |
 13 | */
 14 | define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
 15 | 
 16 | 
17 |

3. Place encode_xml_helper.php in your application/helpers folder (or use your own xml encoder) if you plan on sending back xml.

18 |

4. Place test.php in your application/controllers folder and ajax_test_view.php in your application/views/test folder.

19 | 20 | 21 |

Basic Use

22 |

Example controller (test.php)

23 |
 24 | 
 25 | class Test extends CI_Controller
 26 | {
 27 | 	function __construct()
 28 | 	{
 29 | 		parent::__construct();
 30 | 	}
 31 | 
 32 | 	function index()
 33 | 	{
 34 | 		$this->load->view('test/ajax_test_view');
 35 | 	}
 36 | 
 37 | 	function get_something()
 38 | 	{
 39 | 		$this->load->library('ajax');
 40 | 
 41 | 		$arr['something'] = 'Something Good';
 42 | 
 43 | 		if ($this->input->post('something_id') == '2')
 44 | 		{
 45 | 			$arr['something'] = 'Something Better';
 46 | 		}
 47 | 
 48 | 		$this->ajax->output_ajax($arr);
 49 | 	}
 50 | }
 51 | 
 52 | 
53 | 54 |

The example view: ajax_test_view.php

55 | 56 | 57 |

Options

58 |

You can limit access to HTTP_X_REQUESTED_WITH requests (ajax requests) two ways. The first is by setting the third parameter of output_ajax to TRUE. Note: this the default. If you try to access your ajax url site_url('/test/get_something') via a web browser you will receive the error message: 'Invalid Request Origin'. If you set it to FALSE you will be able to see the data you are returing in your web browser if you are returing text or html, the json and xml types will prompt a file download.

59 |
 60 | 
 61 | function get_something()
 62 | {
 63 | 	$this->load->library('ajax');
 64 | 	$arr['something'] = 'Something Good';
 65 |    
 66 | 	if ($this->input->post('something_id') == '2')
 67 | 	{
 68 | 		$arr['something'] = 'Something Better';
 69 | 	}
 70 | 
 71 | 	$this->ajax->output_ajax($arr, 'json', TRUE);	// Only send a response if this is an ajax request
 72 | }
 73 | 
 74 | 
75 | 76 |

The above method still allows the code in your controler to be executed which is fine for retreving data. If you would like to exit the controler method before any code is executied when this is not an ajax request you can use the non_ajax() method to test it.

77 |
 78 | 
 79 | function get_something()
 80 | {
 81 | 	$this->load->library('ajax');
 82 | 	if ($this->ajax->non_ajax(FALSE)) return;	// Exit the controler if this is not an ajax request
 83 | 	// Optionaly passing TRUE will output a 403 HTTP status code with a text/plain message reading "Invalid Request Origin"
 84 | 	// if ($this->ajax->non_ajax(TRUE)) return; // Exit the controler if this is not an ajax request
 85 | 
 86 | 	$arr['something'] = 'Something Good';
 87 | 
 88 | 	if ($this->input->post('something_id') == '2')
 89 | 	{
 90 | 		$arr['something'] = 'Something Better';
 91 | 	}
 92 | 
 93 |    $this->ajax->output_ajax($arr);
 94 | }
 95 | 
 96 | 
97 | 98 |

Example of an ajax request from a jquery script.

99 |
100 | 
101 | function getServerTime() 
102 | {
103 | 	// Target url
104 | 	var target = 'http://mywebsite.com/controller';
105 | 	
106 | 	// Data to send in post request
107 | 	var data = {
108 | 		command : 'get_server_time'
109 | 	};
110 | 	
111 | 	// Send ajax post request
112 | 	$.ajax({
113 | 		url: target,
114 | 		dataType: 'json',
115 | 		type: 'POST',
116 | 		data: data,
117 | 		success: function(data, textStatus, XMLHttpRequest)
118 | 		{
119 | 			$("#server_time").text(data.server_time);
120 | 		},
121 | 		error: function(XMLHttpRequest, textStatus, errorThrown)
122 | 		{
123 | 			// Error message
124 | 			$("#status").text('Server Error');
125 | 		}
126 | 	});
127 |  }
128 | 
129 | 
130 | 131 |

Tested with CodeIgniter 2.2.0

132 | -------------------------------------------------------------------------------- /test.php: -------------------------------------------------------------------------------- 1 | load->view('test/ajax_test_view'); 13 | } 14 | 15 | function get_something() 16 | { 17 | $this->load->library('ajax'); 18 | 19 | $arr['something'] = 'Something Good'; 20 | 21 | if ($this->input->post('something_id') == '2') 22 | { 23 | $arr['something'] = 'Something Better'; 24 | } 25 | 26 | $this->ajax->output_ajax($arr); 27 | } 28 | } --------------------------------------------------------------------------------