I am using codeigniter-4 version and trying to auto search in nav bar. I'm trying to send data in post method into controller using ajax. But its not work. And codeigniter 4 don't described details for ajax. below my code sample
input box is -
<input class="form-control mr-sm-2" type="search" placeholder="<?= lang('nav.search'); ?>" aria-label="Search" name='s' id="seachBox">
ajax code is -
$.ajax({
url:<?= base_url('search'); ?>,
headers:{'X-Requested-With':'XMLHttpRequest'},
data:{query:query},
success:function(data){
alert(data);
}
});
and my controller is -
<?php
class Search extends BaseController
{
public function __construct()
{
helper(['common_helper','aws_helper']);
}
public function index(){
echo 'string';
}
}
?>
route is -
<?php
$routes->get('/search', 'Search::index');
?>
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']);
}
});
Related
I'm trying to use select2 retrieving large data in my dropdown using the following article.
Getting 500 Internal Server Error in my console log.
I have store token in HTML meta tag.
<meta name="csrf-token" content="{{ csrf_token() }}">
And sending a token as a parameter in my POST request.
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$(document).ready(function(){
$( "#test" ).select2({
ajax: {
url: "path/to/url",
type: "POST",
dataType: 'JSON',
delay: 250,
data: function (params) {
return {
_token: CSRF_TOKEN,
search: params.term // search term
};
},
processResults: function (response) {
return {
results: response
};
},
cache: true
}
});
});
<select class="test" id="test" style="width:100%;"></select>
I have checked routes using php artisan route:list and clear cache using php artisan config:cache. But still getting the same error link. and link.
Is there anything I'm missing? I would be grateful if you can help me out to debug/inspect my Request and Response.
Tried
error: function(err){
console.log(err)
}
Server-Side \ Controller
public function getdata(Request $request){
$search = $request->search;
if($search == ''){
$data = DB::table('table')
->orderby('name','asc')
->select('id','name')
->limit(5)->get();
}else{
$data = DB::table('table')
->orderby('name','asc')
->select('id','name')
->where('name', 'like', '%' .$search . '%')
->limit(5)->get();
}
$response = array();
foreach($data as $i){
$response[] = array(
"id"=>$i->id,
"text"=>$i->name
);
}
return response()->json($response);
}
Happy Coding.
I'm new to programming, and I'm trying to call a function when the user inputs data and clicks submit button. I'm using Yii2 and I'm not familiar with Ajax. I tried developing a function, but my controller action isn't called.
Here is the example code I'm trying:
views/index.php:
<script>
function myFunction()
{
$.ajax({
url: '<?php echo Yii::$app->request->baseUrl. '/supermarkets/sample' ?>',
type: 'post',
data: {searchname: $("#searchname").val() , searchby:$("#searchby").val()},
success: function (data) {
alert(data);
}
});
}
</script>
<?php
use yii\helpers\Html;
use yii\widgets\LinkPager;
?>
<h1>Supermarkets</h1>
<ul>
<select id="searchby">
<option value="" disabled="disabled" selected="selected">Search by</option>
<option value="Name">Name</option>
<option value="Location">Location</option>
</select>
<input type="text" value ="" name="searchname", id="searchname">
<button onclick="myFunction()">Search</button>
<h3> </h3>
Controller:
public function actionSample(){
echo "ok";
}
My problem is that when I click on the Search button nothing happens, and when I try to debug it, the debugger runs no code!
This is sample you can modify according your need
public function actionSample()
{
if (Yii::$app->request->isAjax) {
$data = Yii::$app->request->post();
$searchname= explode(":", $data['searchname']);
$searchby= explode(":", $data['searchby']);
$searchname= $searchname[0];
$searchby= $searchby[0];
$search = // your logic;
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return [
'search' => $search,
'code' => 100,
];
}
}
If this will success you will get data in Ajax success block. See browser console.
$.ajax({
url: '<?php echo Yii::$app->request->baseUrl. '/supermarkets/sample' ?>',
type: 'post',
data: {
searchname: $("#searchname").val() ,
searchby:$("#searchby").val() ,
_csrf : '<?=Yii::$app->request->getCsrfToken()?>'
},
success: function (data) {
console.log(data.search);
}
});
you have to pass _csrf tokin as a parameter
_csrf: yii.getCsrfToken()
or you can disable csrf valdation
The correct way to get the CSRF param is this:
data[yii.getCsrfParam()] = yii.getCsrfToken()
I'm developing a web application which is based on CodeIgniter. I'm new to javascript and JS development. I'm sending post data to a method which is located in a controlle r(homepage/questionview). The data I'm sending to the controller doesn't get posted to the controller. Attached you can see the code I am using. Every attempt I made triggers the AJAX error function.
Html code inside the code I'm calling JS method called viewQuestion(id)
<div class="col-md-7 column list-group">
<a href="" id="list" class="list-group-item active" onclick="viewQuestion(<?php echo $question['questionid']; ?>)">
<h4 class="list-group-item-heading"><?php echo $question['questionid'];echo". "; echo $question['questionTitle']; ?></h4>
<p class="list-group-item-text"><?php echo "Vote Count :"; echo $question['votecount']; ?></p>
<p class="list-group-item-text"><?php echo "Asked user :"; echo $question['username']; ?></p>
</a>
</div>
My JS code
I double-checked the URL used and it's accessible.
<script type="text/javascript">
function viewQuestion(id)
{
$.ajax({
url: '<?php echo base_url(); ?>homepage/questionview',
type: 'POST',
data: { listid: id },
success: function () {
alert('suc');
},
error: function (error) {
// alert('error');
console.log(error);
}
});
}
</script>
homepage/questionview (controller)
public function questionview()
{
//echo $listid;
echo $this->input->post('listid');
}
Few options:
-make sure the onclick event is working, add a alert("test") before the ajax call to make sure you are getting there
-on your controller, try echo "test" to make sure you get the response
-use Chrome console to debug your ajax call and make sure its getting to the controller
Put return false; at the end of the ajax code segment and see. Your code will be like this then.
<script type="text/javascript">
function viewQuestion(id)
{
$.ajax({
url: '<?php echo base_url(); ?>homepage/questionview',
type: 'POST',
data: { listid: id },
success: function () {
alert('suc');
},
error: function (error) {
// alert('error');
console.log(error);
}
});
return false;
}
</script>
I have the code in my view but on sending to my controller action via ajax(as shown in the last part of the add.ctp)
//add.ctp
<?php
echo $this->Form->create('Poll',array('action' => 'index'));
echo $this->Form->input('one', array('id'=>'name'));
echo $this->Form->input('two', array('id'=>'email'));
echo $this->Form->input('three', array('id'=>'message'));
echo $this->Form->input('four', array('id'=>'four'));
echo $this->Js->submit('Send', array('id' => 'btn'), array(
'before'=>$this->Js->get('#sending')->effect('fadeIn'),
'success'=>$this->Js->get('#sending')->effect('fadeOut'),
'update'=>'#success'
));
echo $this->Form->end();
?>
<div id="sending" style="display: none; background-color: lightgreen;">Sending...</div>
<script>
$('#btn').click(function(event) {
form = $("#PollIndexForm").serialize();
// console.log(form);
$.ajax({
type: "POST",
url: 'pollsController/index';,
data: form,
success: function(data){
//
}
});
event.preventDefault();
// return false; //stop the actual form post !important!
});
</script>
on getting to my controller, I made an isAjax request test and if failed
public $components = array('RequestHandler');
public function index(){
$this->autoRender = false;
if($this->RequestHandler->isAjax()){
echo debug('Ajax call');
}
if(!empty($this->data)){
echo debug('not empty');
}
}
I get 'not empty' every time i tried to run this and $this->request->is('ajax') is always false
My version of cakephp is 2.3 and I have tried $this->request->is('ajax') and all that.
I'll appreciate if someone can point out what I am missing out
In your code, you have
if($this->RequestHandler->isAjax()){
Try to make the condition this way:
if ($this->request->is('ajax')) {
}
http://book.cakephp.org/2.0/en/appendices/2-0-migration-guide.html?highlight=isajax#requesthandlercomponent
RequestHandlerComponent: Many of RequestHandlerComponent’s methods are
just proxies for CakeRequest methods. The following methods have been
deprecated and will be removed in future versions: isSsl() isAjax()
isPost() isPut() isFlash() isDelete() getReferer()getClientIp()
Are you sending with your AJAX call the right headers?
{ 'X-Requested-With': 'XMLHttpRequest'}
If you are using jQuery, you can use:
$.ajaxSetup({
headers: { 'X-Requested-With': 'XMLHttpRequest' }
})
You can check it in Chrome developer tools under the network tab, where you must select your request.
and here is the documentation for ajaxSetup()
EDIT:
You can put it here:
<script>
$('#btn').click(function(event) {
form = $("#PollIndexForm").serialize();
$.ajaxSetup({
headers: { 'X-Requested-With': 'XMLHttpRequest' }
})
$.ajax({
type: "POST",
url: 'pollsController/index';,
data: form,
success: function(data){
}
});
event.preventDefault();
// return false; //stop the actual form post !important!
});
</script>
I tried implementing ajax post request in laravel 4, but I am unable to obtain the post data. I have tried implenting both input::get() and input::all().
Here is the ajax code:
$.ajax({
url :url,
type:'POST',
data:{username:username},
dataType:'JSON',
success:function(data){
console.log(data);
}
});
Controller Class code:
class UserController extends Controller
{
// Obtain the response text
protected function _make_response( $response_str, $type = 'application/json' ) {
$response = Response::make( $response_str );
$response->header( 'Content-Type', $type );
return $response;
}
// User Login Function
public function loginAction()
{
// $setting_name = Input::get( 'username' );
$username = Input::get('username');
$response = array(
'username' =>$username,
);
return $this->_make_response( json_encode( $response ) );
}}
I am not able to paste the image here. So I am pasting the result that obtained from Firebug.
POST http://localhost/d/dthKerala/public 200 OK 117ms
Object {...}
But I change the request Type to GET. I am able to obtain the data.
GET http://localhost/d/dthKerala/public?username=render 200 OK 119ms
Object {username="render"}
How can I be able to obtain POST data ?
The mistake you made is sending data with a field value pair called => . Just change data to have a name "username" with value username
$.ajax({
url :url,
type:'POST',
data:{"username":username},
dataType:'JSON',
success:function(data){
console.log(data);
}
});
Hope this helps.
$.ajax(
{
url :url,
type:'POST',
dataType:'JSON',
data:{'username':username},
success:function(data){
console.log(data);
}
});
Will you be able to specify your route portion
Also I would like to suggest to use Response::json() instead of writing more line of codes:
public function loginAction()
{
return Response::json(array('str'=>$response_str))
}