Passing an Ajax variable to a Codeigniter function - codeigniter

I think this is a simple one.
I have a Codeigniter function which takes the inputs from a form and inserts them into a database. I want to Ajaxify the process. At the moment the first line of the function gets the id field from the form - I need to change this to get the id field from the Ajax post (which references a hidden field in the form containing the necessary value) instead. How do I do this please?
My Codeigniter Controller function
function add()
{
$product = $this->products_model->get($this->input->post('id'));
$insert = array(
'id' => $this->input->post('id'),
'qty' => 1,
'price' => $product->price,
'size' => $product->size,
'name' => $product->name
);
$this->cart->insert($insert);
redirect('home');
}
And the jQuery Ajax function
$("#form").submit(function(){
var dataString = $("input#id")
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "/home/add",
data: dataString,
success: function() {
}
});
return false;
});
As always, many thanks in advance.

$("#form").submit(function(){
var dataString = $("input#id")
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "/home/add",
data: {id: $("input#id").val()},
success: function() {
}
});
return false;
});
Notice data option in the ajax method. Now you could use $this->input->post('id') like you are doing in the controller method.

Why not slam it to the end of
url: "/home/add",
like
url: "/home/add/" + $("input#id").val(),
Then I guess codeigniter will treat it like a normal parameter ... ?

Related

Unable to send value through Ajax in Codeigniter 4.1.3

I am using CodeIgniter 4.1.3 for a project. I am facing issue caching value in Controller through Ajax post. Codes are following:
$(document).on('click','#showCont', function(){
var memID=$(this).attr('data-mem');
$data = {memID: memID};
//console.log($data);
$.ajax({
url: "<?=base_url();?>"+"/Member/getContact/",
headers: {'X-Requested-With': 'XMLHttpRequest'},
type: "POST",
data: $data,
cache: false,
success: function (cont) {
console.log(cont);
}
});
});
And here is the Controller:
<?php
namespace App\Controllers;
use App\Controllers\BaseController;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use App\Models\Project_model;
use App\Models\General_model;
use CodeIgniter\I18n\Time;
class Member extends BaseController {
public function getContact(){
if ($this->request->isAJAX()) {
// echo "Hi"; printing Hi in console
//echo $query = $this->request->getPost('memID'); // returning nothing
print_r($_REQUEST);
}
}
And the route:
$routes->post('Member/getContact)', 'Member::getContact');
Below is the response of print_r in console.log
Array
(
[__tawkuuid] => e::xxxdomainxxx.com::FtBr5/am9LXZ8gvI7KxyHJZ279zLJEw11KZhdGh+4sflsIqrslML4R2NgRYqN8Vc::2
[__utmz] => 120264590.1625144765.12.5.utmcsr=l.facebook.com|utmccn=(referral)|utmcmd=referral|utmcct=/
[_ga] => GA1.2.2142405146.1621409499
[__utmc] => 120264590
[__utma] => 120264590.2142405146.1621409499.1629910859.1629978516.31
[_gid] => GA1.2.1913990981.1630182229
[ci_session] => e27a1e9ce4d0ee37f9b6569bd8eb15ab77fe45b2
)
Unable to understand why print_r $_INPUT is not showing sent data. Can anyone help me to solve this issue?
You are not writing the ajax correctly, you are going to have to pass the parameter in the url
$(document).on('click','#showCont', function(){
var memID=$(this).attr('data-mem');
$data = {memID: memID};
//console.log($data);
$.ajax({
url: "<?=base_url();?>"+"/Member/getContact/" + "<?=$data?>",
headers: {'X-Requested-With': 'XMLHttpRequest'},
type: "GET",
cache: false,
success: function (cont) {
console.log(cont);
}
});
});
On the other hand if you are using codeigniter 4 csrf validation, the method cannot be POST, you will have to use GET.

Ajax update field database field in laravel blade template

I have a list of hotels in a select I want update the database base on the hotel selected if it update the field I want to alert it on the home page.
this is the ajax function
function showRoom($hotel_plan_id) {
var id = $hotel_plan_id;
if (id !== "") {
$.ajax({
type: "POST",
dataType: 'JSON',
url:'{{ route('home', '') }}/'+id,
data:{_token:'{{ csrf_token() }}'},
success:function(data){
alert(data);
},
error: function (result) {
alert("Error occur in the update()");
}
});
}
}
my controller
public function update(Request $request, $hotel_plan_id)
{
$hotel=plan_hotel::where('hotel_plan_id', $hotel_plan_id)->first();
$hotel->hotel_name = $request->input('hotel_name');
//$hotel ->room_name = $request->input('room_name');
$hotel->save();
// return redirect('/home')->with('success', 'price updated');
}
my route
Route::post('home/{hotel_plan_id}', 'HomeController#update')->name('home');
my select form
{!! Form::select('hotel_name', array($item[4], $item[10]),'S', array('style'=>' Border:none; ', 'id' => 'hotel_id', 'onclick'=>"showRoom(this.value, $item[8])"));!!}
You have error with ajax url and you dont also pass the value of hotel name.
Check this changes.
function showRoom($hotel_plan_id) {
var id = $hotel_plan_id;
if (id !== "") {
$.ajax({
type: "POST",
dataType: 'JSON',
url:'/home/' + id,
data:{_token:'{{ csrf_token() }}', hotel_name: 'Your value here'},
});
}
Please return json response
return response()->json();
You have to return json object like this
return response->json([
'status' => 200,
'result' => true,
'error' => false,
'data' => $hotel
]);

laravel- request empty in controller using ajax

I am using laravel 6.0 and i am building crud application. I have following jquery code in view file
function updaterecord(id) {
$('#modalupdate').on('submit', function (e) {
e.preventDefault();
$.ajax({
url: 'update/'+id,
method: 'post',
success: function (res) {
console.log(res);
}
})
});
}
And this is the code in controller
public function update(Request $request, $id='') {
$country = $request->input('countryname');
$sortname = $request->input('sortname');
$phonecode = $request->input('phonecode');
//return $country.$sortname.$phonecode;
return $request;
// DB::table('countries')->where('id',$id)->update(
// [
// 'name' => $country,
// 'sortname' => $sortname,
// 'phonecode' => $phonecode,
// ]);
}
The problem is $request returns empty.
If I don't use ajax then I am getting all input values. But I dont know why its not working for ajax request. Also I have added this line in view file
headers: {
'X-CSRF-TOKEN': '{!! csrf_token() !!}'
}
});
Please help me to solve this problem
You are not passing your form data. Try this:
function updaterecord(id) {
$('#modalupdate').on('submit', function (e) {
e.preventDefault();
$.ajax({
url: 'update/' + id,
method: 'post',
data: $(this).serialize();
success: function (res) {
console.log(res);
}
})
});
}
laravel by default does not send raw data , you have to convert your data to json, the best practice is :
return response()->json([
'data' => $request
]);
Just try this code for example and see if you get any hint.
function updaterecord(id) {
$('#modalupdate').on('submit', function (e) {
e.preventDefault();
$.ajax({
url: 'update/' + id,
method: 'post',
data: {'countryname' : 'India','sortname' : 'Sort Name', 'phonecode' : '022'};
success: function (res) {
console.log(res);
}
})
});
}
See if you are getting any response.

Redirecting to different view after an AJAX call Laravel

I am trying to activate my user by doing an AJAX call. I have this jQuery code for that:
$(document).ready(function(){
$(document).one('click','.continue-button',function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var id = $(this).data('id');
$.ajax({
url: '/activate',
type: 'POST',
data: {id : id},
success: function(res){
}
});
});
});
It takes the data-id attribute of my button, which is the user's id and sends an AJAX call. This is how my route looks like:
Route::post('/activate','ActiveController#activate');
My function:
public function activate(Request $request)
{
$id = $request->input('id');
User::where('id',$id)->update([
'active' => '1'
]);
return redirect('/loadDashboard');
}
It activates the user and then redirects to '/loadDashboard' route. This is how the route looks like:
Route::group( ['middleware' => 'auth' ], function()
{
Route::get('/loadDashboard','ActiveController#loadDashboard');
});
And finally my loadDashboard function:
public function loadDashboard()
{
return view('dashboard')->with('title','Dashboard');
}
I want to redirect the user to my dashboard view in aforementioned function, but it seems to return the view to my AJAX call. I can see the view in Inspect->Network. How can I fix this problem?
Instead of this
return redirect('/loadDashboard');
put this
return response()->json(['url'=>url('/loadDashboard')]);
and in your ajax success function put this:
success: function(res){
window.location=res.url;
}

ajax not getting any response from cakephp code

I am using CakePHP 2.9 to send data on the URL using ajax and get the related response.
I tried may method to get the response, I also want to know why this //URL:'/Pages/dropdownbox/'+id is not working.
bellow are ajax code which I wrote in the index.ctp.
$("#certificatedetail").on('change',function() {
var id = 'subcribe';
$("#usertype").find('option').remove();
$("#certificateclass").find('option').remove();
$("#certificatetyp").find('option').remove();
if (id) {
$.ajax({
type: 'POST',
url:'<?= Router::url(array('controller' => 'Pages', 'action' => 'dropdownbox','id')); ?>',
//url:'/Pages/dropdownbox/'+id,
dataType:'json',
cache: false,
async:true,
success: function(html)
{
$('<option>').val('').text('select').appendTo($("#usertype"));
$('<option>').val('').text('select').appendTo($("#certificateclass"));
$('<option>').val('').text('Select').appendTo($("#certificatetyp"));
$.each(html, function(key, value)
{
$('<option>').val(key).text(value).appendTo($("#usertype"));
});
}
});
}
});
I have written this controller code in PagesController,PHP and I declared the dropdownbox in AppController.php
public function dropdownbox($id = null)
{
Configure::write('debug', 0);
$this->layout = null;
$this->autoRender = false;
$category = array();
switch ($id)
{
case $id == "subcribe":
if ($id == 'subcribe') {
$category = array(
'individual' => 'Individual',
'organization'=>'Organization',
'organizationgovt' => 'Organization-Govt',
'organizationbank' => 'Organization-Bank'
);
break;
}
}
}
/ bellow is the code where I specify the dropdownbox function in AppController.php
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow(
'login','add','index','contact','dropdownbox',
'cityres','stateres','sectorres','productres',
'project','service','about','apply','tender',
'decregistration','search','searchresult',
'tenderdetails'
);
}
You are generating the URL on your server, and using the string literal 'id' in it. The JavaScript id variable is never referenced. What you probably want is:
url:'<?= Router::url(array('controller' => 'Pages', 'action' => 'dropdownbox')); ?>' + id,
You are not returning any response from the controller. Do few things to debug it
Check in Browser's Network tab whether the called URL is correct or not.
Check the parameters are correct or not.
This is how it looks in Firefox Developer Edition
If URL is correct. Add below code in the dropdownbox() method. (Before the closing of the method)
echo json_encode($category);
Check Response Tab in the Network tab. (Example image above).
Also, console the response in the javascript code. Maybe you will be getting some other response which is not JSON.
success: function(html) {
console.log(html);
...
}
Hope it helps.

Resources