Unable to send value through Ajax in Codeigniter 4.1.3 - ajax

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.

Related

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.

Laravel: Ajax update to database

i just want to update my data via ajax i am getting error.
Error Console:
POST http://abc.local/teachers/users/1 404 (Not Found)
here is my controller:
public function policyupdate(Request $request, $id)
{
$user = DB::table('users')->find($id);
$user->update($request->all());
return response()->json([
'status' => 'success',
'msg' => 'has been updated'
]);
}
web.php:
Route::post('users/{user}','TeachersController#policyupdate') ;
js:
jQuery(document).ready(function(e) {
alert(1);
$('#update-policy').on('click', function(e) {
console.log('Update policy clicked!')
e.preventDefault(e);
$.ajax({
type: "POST",
url: "users/" + $('#update-policy').attr("value"),
data: $(this).serialize(),
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function (data) {
alert(updated);
},
});
});
});
I only notice a couple of issues.
url: "users/" + $('#update-policy').attr("value"),
In the url of the ajax call you don't have a slash at the beginning, so the url will be relative to the url of the page where the function is located, instead of the base url. to solve it just add that slash at the beginning
url: "/users/" + $('#update-policy').attr("value"),
The other one is that you have an input with the put method,
<input type="hidden" name="_method" value="put" />
so the Laravel route should be put (it makes sense if it takes into account that it is a route to update)
Route::put('users/{user}','TeachersController#policyupdate') ;
Well, and as you yourself discovered, with query builder, the update() method works if you query with where() instead of find()
$user = DB::table('users')->where('id', $id)->update( $request->all() );

Cannot insert ajax data into database codeigniter

I want to insert some ajax post data into database. But when I'm clicking submit, no data is being inserted.
view(header.php)
$(function(){
$(".submit").click(function(){
transaction_student_id=$(".student_id").val();
transaction_particular_name=$(".particular_name").val();
transaction_id=$(".transaction_id").val();
jQuery.ajax({
type: "POST",
url: "<?php echo base_url().'user/add_transaction'; ?>",
dataType: 'json',
data: {transaction_student_id: transaction_student_id,transaction_particular_name:transaction_particular_name,transaction_id:transaction_id},
success: function(data) {
}
});
});
});
Controller (User.php)
public function add_transaction()
{
$columns_and_fields = array('transaction_id','transaction_particular_name','transaction_student_id');
foreach ($columns_and_fields as $key)
$data[$key]=$this->input->post($key);
$query=$this->Mdl_data->insert_transaction($data);
if($query)
redirect('User','refresh');
}
Model (Mdl_data.php)
public function insert_transaction($data=array())
{
$tablename='transaction';
$query=$this->db->insert($tablename,$data);
return $query;
}
First of all, declare the variable in JavaScript with keyword var
var transaction_student_id=$(".student_id").val();
Before starting the Ajax use console.log() to know if the variables have data or not
The second thing is you are not getting the data with right way in the controller
Try like this
public function add_transaction()
{
$columns_and_fields = array('transaction_id' = $this->input->post('transaction_id'),
'transaction_particular_name' => $this->input->post('transaction_particular_name'),
'transaction_student_id' => $this->input->post('transaction_student_id'));
$query=$this->Mdl_data->insert_transaction($columns_and_fields);
if($query){
redirect('User','refresh');
}
}
Don't use the extra line of code without any reason
public function insert_transaction($data = array())
{
return $this->db->insert('transaction', $data);
}
Try debugging your code first.
Do you get all the data in controller? Try to dump POST values var_dump($_POST) in controller if ajax is successfully sending the data.
From there, you can see if the data in successfully sent from the front end.
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>user/add_transaction",
dataType: 'json',
data: {
transaction_student_id: transaction_student_id,
transaction_particular_name: transaction_particular_name,
transaction_id: transaction_id
},
success: function( data ) {
console.log( data );
},
error: function( xhr, status ) {
/** Open developer tools and go to the Console tab */
console.log( xhr );
}
});
change it
$(function(){
$(".submit").click(function(){
transaction_student_id=$(".student_id").val();
transaction_particular_name=$(".particular_name").val();
transaction_id=$(".transaction_id").val();
jQuery.ajax({
type: "POST",
url: "<?php echo base_url().'user/add_transaction'; ?>",
dataType: 'json',
data: {transaction_student_id: transaction_student_id,transaction_particular_name:transaction_particular_name,transaction_id:transaction_id},
success: function(data) {
alert(data + ' id added' );
window.location.reload(); // force to reload page
}
});
});
});
at controller
public function add_transaction()
{ // use it only for ajax call or create another one
$columns_and_fields = array();
// 'transaction_id','transaction_particular_name','transaction_student_id'
foreach ($_POST as $key)
{
array_push($columns_and_fields , array(
'transaction_student_id' => $key['transaction_student_id'],
'transaction_particular_name'=>$key['transaction_particular_name'],
'transaction_id'=>$key['transaction_id']
)
);
}
$this->Mdl_data->insert_transaction_array($columns_and_fields);
}
and at model create new method
public function insert_transaction_array($data=array())
{
$tablename='transaction';
$this->db->insert_batch($tablename,$data);
}

How to pass array of data to controller?

I'm new here :). I have a problem with my code. I'm working with laravel 5.1 and Blade. In my view I have:
function getNumber(){
values = [];
values[0] = $('#receipt_type_id').val();
values[1] = $('#provider_id').val();
$.ajax({
url: "{{{ url('receipts/showByNumber') }}}",
type: "get",
data: {ids: values},
dataType: "json",
success: function (data) {
//i do something
}
});
}
In my route:
Route::get('receipts/showByNumber', ['as' => 'receipt.showByNumber', 'uses' => 'ReceiptsController#showByNumber']);
And in my controller:
public function showByNumber($values){
$receipt_type_id = $values[0];
$provider_id = $values[1];
//Find the receipt to edit
...
...
}
The error is GET http://manchego.app/receipts/showByNumber?ids%5B%5D=1&ids%5B%5D=2 500 (Internal Server Error). I read another topics with the same problem that I have but I can't understand where is my problem.
Thanks in advance! :)
You could type-hint the Request class (recommended):
public function showByNumber(\Illuminate\Http\Request $request)
{
$allParams = $request->all(); // returns an array
$provider_id = $request->get('provider_id');
}
Or you could use the Request facade:
public function showByNumber()
{
$allParams = \Request::all(); // returns an array
$provider_id = \Request::get('provider_id');
}

Passing an Ajax variable to a Codeigniter function

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 ... ?

Resources