How do I check if the request is made via AJAX in CodeIgniter?
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!
}
Check for Ajax request in CodeIgniter
You can use $this->input->is_ajax_request()
from the input class:
if (!$this->input->is_ajax_request()) {
exit('No direct script access allowed');
}
Check if AJAX call is success or not in codeigniter
You need to check data is inserted or not in database using affected_rows in model
Model
function insert_truck($data){
$this->db->insert('trucks', $data);
$afftectedRows=$this->db->affected_rows();
if($afftectedRows>0)
{
return TRUE;
}
else{
return FALSE;
}
}
YOu need to echo your result in Controller
Controller
function add_truck() {
$data = array(
'user_id' => $this->input->post('user_id'),
'marca' => $this->input->post('marca'),
'serie' => $this->input->post('serie'),
'numar' => $this->input->post('numar')
);
//Transfering data to Model
$res=$this->trucks_model->insert_truck($data);
if($res){
$data['msg'] = 'true';
}else{
$data['msg'] = 'false';
}
echo json_encode($data);
}
Ajax
success: function (res) {
if (res.msg=='true')
{
jQuery("div#truck_form").hide();
jQuery("div#success").show();
} else {
jQuery("div#error").show();
}
}
How to use ajax in codeigniter 4
Here is the sample code of ajax. (Make sure that you have defined route/controller method for search url)
$.ajax({
url:<?php echo base_url('search'); ?>,
type: 'post',
dataType:'json',
data:{query:query},
success:function(data){
alert(data);
}
});
CI4 Code to get the request data
if ($this->request->isAJAX()) {
$query = service('request')->getPost('query');
var_dump($this->request->getPost('query'));
}
Also, make sure to update csrf token
on every request if you are not reloading a page on success. Also, you need to return csrf
token in method.
So in that case your method will look like -
if ($this->request->isAJAX()) {
$query = service('request')->getPost('query');
//var_dump($this->request->getPost('query'));
return json_encode(['success'=> 'success', 'csrf' => csrf_hash(), 'query ' => $query ]);
}
So in that case your ajax code will look like -
$.ajax({
url:<?php echo base_url('search'); ?>,
type: 'post',
dataType:'json',
data:{query:query},
success:function(data){
var result = JSON.parse(data);
$("input[name='csrf_test_name']").val(result['csrf']);
}
});
Way to tell if a post came from an ajax call in codeigniter?
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest')) {}
But since you are using codeigniter, its better to use their input class . See how to do it below.
if($this->input->is_ajax_request()){
//Execute Your Code
}
How to check if the request is an AJAX request with PHP
There is no sure-fire way of knowing that a request was made via Ajax. You can never trust data coming from the client. You could use a couple of different methods but they can be easily overcome by spoofing.
Related Topics
PHP Keep Checkbox Checked After Submitting Form
Parametrized Pdo Query and 'Limit' Clause - Not Working
Reordering Checkout Fields in Woocommerce 3
Html,PHP - Escape '<' and '>' Symbols While Echoing
How to Access a Deep Object Property Named as a Variable (Dot Notation) in PHP
Is There a Good PHP Geolocation Service
PHP Simplexml Namespace Problem
How to Get Insert Id in Mssql in PHP
Pg_Query Result Contains Strings Instead of Integer, Numeric
Preg_Match() Unknown Modifier '[' Help
I Cannot Use MySQL_* Functions After Upgrading PHP
Best Way to Allow Plugins for a PHP Application
What Are the Differences Between Psr-0 and Psr-4
Understanding Ioc Containers and Dependency Injection
How to Throttle My Site's API Users
Get Array's Key Recursively and Create Underscore Separated String