Codeigniter: AJAX request don't have response data - ajax

I have a simple app in codeigniter. In my view I have ajax POST request to the controller, but I don't receive response data. I checked in the chrome dev tool in network tab the response and the message is: No response data available for this request :
My view:
<table class="table table-striped table-bordered">
<thead>
<tr>
<td>First</td>
<td>Sec</td>
<td>Th</td>
<td>Th</td>
</tr>
</thead>
<tbody>
<?php
if(isset($result))
{
foreach($result as $value)
{
echo "<tr><td>". $value->cai . "</td><td>". $value->partner ."</td><td>". $value->spot ."</td><td><button type='button' id='".$value->cai."' class='btn btn-danger delete'>Delete</button></td></tr>";
}
}
?>
</tbody>
</table>
<?php echo $this->pagination_bootstrap->render(); ?>
<script>
$('.table').on('click','.delete',function(){
var id=$(this).attr('id');
var confirm_box=confirm('Sure?');
if(confirm_box === true)
{
$.ajax({
url: '<?php echo site_url('Tires_Crud/deleteCai'); ?>',
type: 'POST',
data: {
key: id
},
dataType: 'json',
success: function(data) {
console.log(JSON.parse(data));
}
});
}
});
</script>
My controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Tires_Crud extends MY_Controller
{
public function deleteCai()
{
$status = array(
"STATUS" => "true"
);
return json_encode($status);
}
}
In my config file CSRF protection is DISABLED! Because when its enabled the ajax request is not working. Thanks for your help in advance!

Some issues with this code.
#1: The way you're forming the ajax request. Where you have type: 'POST' should be method: 'POST' - but more than a typo, it's important that you understand these are referred to as the HTTP method - same way you'd specify that in a <form method='post' tag. If you don't provide a method, it's assumed to be GET.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods
Also, because you specified dataType:'json' - jquery will deliver a ready to use parsed JSON object. No need for you to parse it yourself
$.ajax({
url: '<?php echo site_url('Tires_Crud/deleteCai'); ?>',
method: 'POST', // <-- change this from 'type' to 'method'
data: {
key: id
},
dataType: 'json',
success: function(data) {
// console.log(JSON.parse(data)); // <-- no need to parse - you have set dataType to be json, which means it will come to you already parsed
console.log(data);
})
#2 - In your PHP, you'd catch your key variable (you sent in ajax) with $_POST['key'] - though in codeigniter you get it like this:
// codeigniter 2.x and 3.x
$this->input->post('key');
// codeigniter 4
use CodeIgniter\HTTP\IncomingRequest;
$request = service('request');
$request->getPost('key');
#3 - With ajax, you actually echo the response, rather than return it:
public function deleteCai(){
$status = array(
"STATUS" => "true"
);
echo json_encode($status);
}

Related

Post 403 forbidden on Yii2 Ajax Call

I know there's other topic on this in stackoverflow but it still didn't work for me. I try to make a simple dynamic menu that generate dynamic content based on the chosen <li> id.
This is the code to generate the menu :
foreach($cabang as $index=>$model){
echo '<li id='.$model->idDpd->id_dpd.'>
<a class="nav-link" href="#" role="tab" data-toggle="tab">'.$model->idDpd->dpd.'</a>
</li>';
}
The menu is created successfully. But I have the problem with the content generated with Ajax
This is what I have in my view file :
$script = <<< JS
$(document).ready(function(){
function load_page_details(id)
{
$.ajax({
url: "<?=Url::to(['/site/fetch']) ?>",
method:"POST",
data:{id:id}, //pass the 'id' of Load_page_details function parameter to the targeted URL
success:function(data)
{
$('#page_details').html(data);
}
});
}
//load page-details where the id in the database table equals 1. Set the default to 1 while page is loading for the first time.
/* load_page_details(1);*/
$('.nav li').click(function(){
var page_id = $(this).attr("id");
load_page_details(page_id);
});
});
JS;
$this->registerJs($script)
?>
This is my SiteController and the action :
public function actionFetch(){
if (Yii::$app->request->isAjax) {
// fetch the $_POST["id"]
$data = Yii::$app->request->post('id');
if(isset($data))
{
$query= Cabang::find()->where(['id_dpd'=> $data])
->joinWith('idDpd')
->all();
$output = '';
foreach($query as $model)
{
$output .= '
<div role="tabpanel" class="col-lg-4 tab-pane fade show active" >
<div class="col-md-12">
<h4>'.$model->kota.'</h4>
<p>'.$model->alamat.'</p>
<p>'.$model->telp.'</p>
<p>'.$model->email.'</p>
<p>'.$model->jadwal.'</p>
</div>
</div>
';
}
/* echo $output;*/
// return Json
return \yii\helpers\Json::encode($output);
}
}
}
The error caught in my console in chorome dev tool : jquery.js:9175 POST http://localhost/%3C?=Url::to([%27/site/fetch%27])%20?%3E 403 (Forbidden)
I tried to make the fetch function to a new php file and link the URL in my Ajax to that file (not to a controller or SiteController in my case) like : url: url:"site/fetch.php",but it returned jquery.js:9175 POST http://localhost/site/fetch.php 404 (Not Found)
What am I doing wrong? I have spent two days without solution. Thanks for the help!
Your PHP is not correct - you cannot use <?= /* ... */ ?> inside of heredoc. You need to use temporary variable:
$url = Url::to(['/site/fetch']);
$script = <<<JS
$(document).ready(function () {
function load_page_details(id) {
$.ajax({
url: "$url",
method: "POST",
data: {id: id}, //pass the 'id' of Load_page_details function parameter to the targeted URL
success: function (data) {
$('#page_details').html(data);
}
});
}
$('.nav li').click(function () {
var page_id = $(this).attr("id");
load_page_details(page_id);
});
});
JS;
$this->registerJs($script);

Return view json response

I try to pass a return json to my view but I get an error who say that I didn't past all the variables objects to the view, the problem if I pass all the variables in my table I get all my web page in the table wish is no sense..
someone know how I could do?
here my controller:
public function searchEquipes(Request $request)
{
if ($request->has('poule_id')) {
$equipes = EquipePoule::where('poule_id' , $request->poule_id)->get();
return response()->json([
'table' => view("competitions/show", compact('equipes'))->render(),
]);
}else {
//nothing
}
}
here my view:
#foreach($equipes as $equipe)
<tr>
<td>{{$equipe->equipe->structure->nom_structure}}</td>
<td>{{$equipe->equipe->lb_equipe}}</td>
<td>{!! Form::text('nb_bonus') !!}</td>
</tr>
#endforeach
here my script:
<script>
$('#poule').change(function () {
$.ajax({
type: 'GET',
url : 'search/equipes',
dataType: "json",
data : {
poule_id : document.getElementById('poule').value
},
success:function(data){
$('#equipes').html(data.table);
}
});
});
</script>
i guess you are not returning the json response the right way try using
return response()->json([$equipes]);
success:function(data){
//loop $equipes here
}

Ajax jquery.min.js:4 POST 500 (Internal Server Error) laravel 5

I got this error from Ajax call ! it's get action from checkbox then send data by Ajax to controller method,
jquery.min.js:4 POST http://localhost:8000/listhotelregisration 500 (Internal Server Error)
Here's the code html part:
<div style="display:block">
<div>My hotel Lists</div>
#foreach($myLists as $key => $val)
{{ $val['name'] }
{!! Form::checkbox($val['name'], $val['id'].','.$value['id']) !!} <br>
#endforeach
</div>
Ajax part:
$(function() {
$("input[type='checkbox']").change(function() {
var smi = $(this).val();
// alert(smi);
$.ajax({
url: 'listhotelregisration',
type: "post",
data: {'checko':smi},
success: function(data){
//alert(data);
}
});
});
Route part:
Route::post('listhotelregisration', 'ListhotelController#create');
Controller part:
public function create(Request $request)
{
$listhotel = new listhotel;
$data = $request->all();
$dataPrim = explode(",", $data);
$listhotel->id_list= $dataPrim[0];
$listhotel->id_hotel= $dataPrim[1];
$listhotel->save();
$response = "ok";
return response ()->json ($response);
}
Ajax in Laravel 5
This is mainly due to The VerifyCSRFToken middleware that laravel provide us out-of-the-box. It responds an Internal Server Error (500) when token mismatch occur on our requests.
We need to send our AJAX request with token sent to our browser.
The CSRF token is mostly stored in the meta tag, you can put it any where though
$.ajaxSetup
Set default values for future Ajax requests
Solution
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
});
Hope this helps.
error 500 will mean this is a server error.
To know exactly what went wrong you need to check the response the server is returning.
In any case i would already adjust your following pieces:
Javascript:
$(function() {
$("input[type='checkbox']").change(function() {
var id_list = $(this).attr('id_list');
var id_hotel = $(this).attr('id_hotel');
$.ajax({
url: 'listhotelregisration',
type: "post",
data: {
'id_list': id_list,
'id_hotel':id_hotel
}
}
});
});
Controller:
public function create(Request $request)
{
$data = $request->only(['id_list', 'id_hotel']);
$listhotel = listhotel::firstOrCreate($data)
return response ()->json ("OK");
}

how to send ajax request to codeigniter library file or class

ajax code
function autocomplet(){
var countryname= $('#countrysearch').val();
$.ajax({
type: 'POST',
url: 'My_commonlib', // My_commonlib is library file in library folder
data: "countryname=" + countryname,
success: function(data){
}
});
}
html code
<input type="text" onkeyup="autocomplet()" class="inputs form-control " style=" border-bottom: .5px solid;" id="countrysearch" name="countrysearch" placeholder=" Search">
I send a request to My_commonlib in library folder
php code
Pass ajax request to this class My_commonlib or method getcountry
class My_commonlib {
private $ci;
public function __construct()
{
$this->ci=& get_instance();
$this->ci->load->database();
// parent::__construct();
}
function getcountry(){
$this->ci->db->from('countries');
$this->ci->db->order_by("country", "ASC");
return $this->ci->db->get()->result();
}
}
and get in view file as
$a = new My_commonlib();
$results=$a->getcountry();
foreach ($results as $row)
{ ?>
<?php echo $row->country ; ?><br>
<?php }
?>
Change :
url: 'My_commonlib',
to
url: '<?php echo base_url('My_commonlib/getcountry');?>',
CodeIgniter uses the url to decide which controller to load. You will always handle requests with a controller. The controller can be a very thin object that loads the library and passes the request on to it.

Symfony ajax form need reload page to show results

I have a product page where users can write comments, this works fine but i would like to implement ajax form with no page refresh.
The code call ajax and persist, but need press f5 to show new comment.
what am I doing wrong?
Thanks, and sorry for my english.
In product view, render a controller that call the form:
<div class="comments">
{{ render(controller('AppBundle:Comment:newComment',{'media': selected.id})) }}
</div>
Controller:
class CommentController extends Controller
{
/**
* #Route("/media/{media}/", name="create_comment", options={"expose"=true})
* #Method("POST")
* #ParamConverter("media", class="AppBundle:Media")
*/
public function newCommentAction(Request $request, $media)
{
$comment = new Comment();
$form = $this->createForm(CommentType::class, $comment);
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()){
$data = $form->getData();
$data->setUser($this->getUser());
$data->setMedia($media);
$em = $this->getDoctrine()->getManager();
$em->persist($data);
$em->flush();
return new JsonResponse('Success!');
}
return $this->render('comment/newComment.html.twig', array(
'media' => $media,
'form' => $form->createView()
));
}
}
newComment.html.twig
<form method="POST" id="commentForm" action="{{path('create_comment', {'media': media.id})}}">
{{ form_row(form.comment) }}
<button type="submit" id="submitButton" class="btn btn-xs btn-danger">{{ 'btn.send' |trans }}</button>
app.js
$('body').on('click','#submitButton', function(e){
e.preventDefault();
var $form = $('#commentForm');
$.ajax({
type: "POST",
dataType: "json",
url: 'http://demo/app_dev.php/media/16/',
data: $form.serialize(),
cache: false,
success: function(response){
$(".ajaxResponse").html(response);
console.log(response);
},
error: function (response) {
console.log(response);
}
});
});
This should work for you to reload the element with class="comments" after your POST:
$('#submitButton').on('click', function (e) {
e.preventDefault();
var $form = $('#commentForm');
$.ajax({
type: "POST",
dataType: "json",
url: 'http://demo/app_dev.php/media/16/',
data: $form.serialize(),
cache: false,
success: function (response) {
$('.comments').load(window.location + ' .comments > *');
console.log(response);
},
error: function (response) {
console.log(response);
}
});
});
Edit:
As far as your second question regarding $request->isXmlHttpRequest() -- this method just looks for the X-Requested-With header with value of XMLHttpRequest. Are you testing for it on the first request or on the second request or on both requests? Can you take a look in Firebug or Chrome Tools and see if the header is on both requests?

Resources