How to pass array of data to controller? - ajax

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');
}

Related

How to return resonse from ajax and display it in Blade file in laravel 8

I am trying to integrate sorting system in laravel application, I am able to do ajax call and got the response but how to display that data in blade file.
I have the data already displayed on search page now if user try to sort the and old data will replaced by the new data.
How can I do that.
Controller Code :
public function sort_data(Request $request){
$results='';
if(request()->sub_sub_category){
$results = Product::orderBy($request->sorting_selection,'asc')->with('categories')->whereHas('categories', function ($query){
$query->where('slug', request()->sub_sub_category);
})->paginate(24);
} elseif (request()->sub_category){
$results = Product::orderBy($request->sorting_selection,'asc')->with('categories')->whereHas('categories', function ($query){
$query->where('slug', request()->sub_category);
})->paginate(24);
} elseif (request()->category){
$results = Product::orderBy($request->sorting_selection,'asc')->with('categories')->whereHas('categories', function ($query){
$query->where('slug', request()->category);
})->paginate(24);
} else{
$results = Product::orderBy($request->sorting_selection,'asc')->with('categories')->paginate(24);
}
// $returnHTML = view('pages.user.shop.products.products')->with(["products"=>$results])->render();
// return response()->json(array('success' => true, 'html'=>$returnHTML));
// return response()->json(['products' => $results, 'status' => 200]);
return view('pages.user.shop.products.products')->with(["products"=>$results]);
}
I have already tried the commented code. But not success
$(document).ready(function(){
$('#soting-select').on('change', function(){
var value = document.getElementById('soting-select').value;
var ajaxurl = '/sort-product';
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: ajaxurl,
type: 'post',
dataType: 'json',
data: {
'sorting_selection' : value
},
success: function(response){
console.log(response);
}
});
});
});
Old Response :
New Response :
You can call render() on the view.
And also you may need to change the $results variable to $products as you have shared the data with $products variable in your blade file.
$returnHTML = view('pages.user.shop.products.products', compact('products'))->render();
See the View source code for more information.

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.

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.

How get data from ajax object in controller Laravel?

In ajax I have 3 objects 'emp_info, leave_detail, and leave_items' in controller I don't know how to get record of each object. Could you help me please?
$.ajax({
type: 'POST',
url: '/leave-request-initiator/store',
data: {_token: $('#_token').val(), emp_info: $('#frm_emp_info').serialize(), leave_detail: $('#frm_leave_detail').serialize(), leave_items: leave_items},
beforeSend: function () {
console.log('sending');
},
success: function (response) {
console.log(response);
}
});
Controller.
public function store(Request $request)
{
$data = $request->all();
foreach ($data->emp_info as $item){
$empcode = $item['EMPCODE'];
}
$leaveDetail = new HREmpLeave([
'EMPCODE' => $empcode,
'LEAVECODE' => $request->get('LEAVECODE'),
'FROMDATE' => $request->get('FROMDATE'),
'TODATE' => $request->get('TODATE'),
'BACKTOWORKON' => $request->get('BACKTOWORKON'),
'NODAY' => $request->get('NODAY'),
'REMARK1' => $request->get('REMARK1')
]);
$leaveDetail->save();
}
Change this:
$data = $request->all();
foreach ($data->emp_info as $item){
$empcode = $item['EMPCODE'];
}
to this:
$emp_info = parse_str($request->emp_info); //parse into a array
$empcode = $emp_info['EMPCODE'];

How to edit records of two tables at the same time in cakephp 3?

I need help: I do not know how to edit two tables of the database from the same form. I'm using cakephp3.
I'm trying to use ajax
Thanks for your help
Data to save in a different driver, there the script
This script is in a controller called carsController
**<script type="text/javascript">**
function editarCliente(a, b ){
var parametros = {
"clasificacionC" :a,
"descripcion": b,
};
$.ajax({
data: parametros,
url: '<?php echo router::url(array('controller'=>'Clientes','action'=>'editarcliente',$cliente->id));?>',
type: 'post',
dataType: 'json',
success: function (response) {
$("#nomCliente").val(response.uno+" "+response.dos);
$("#telCliente").val(response.tres);
$("#celCliente").val(response.cuatro);
}
});
}
**</script>**
This method is in a controller called clientesController.
public function editarcliente($id = null)
{
$cliente = $this->Clientes->get($id, [
'contain' => []
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$cliente->clasifi_cliente=$_POST("clasificacionC");
$cliente->descripcion=$_POST("descripcionC");
if ($this->Clientes->save($cliente)) {
$this->Flash->desactivar(__('Cliente desactivado'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The cliente could not be saved. Please, try again.'));
}
}
$this->set(compact('cliente'));
$this->set('_serialize', ['cliente']);
}

Resources