Codeigniter: How to print array of arrays from view to model - codeigniter

I have an ajax where it passes the array of arrays or multidimensional/2 dimensional array and when I passed it to controller to model, I need to do a Foreach inside a function so that I can get the $this->input->post('distance'); but I don't know how can I print the array of arrays in the model or get the array of arrays so that I can do a Foreach.
here is my ajax:
$.ajax({
url: url + 'getBookTours',
type: 'POST',
data: data,
success: function(data, textStatus, jqXHR) {
swal("Booked!", "", "success");
},
error: function(jqXHR, textStatus, errorThrown) {
swal("Save Error!", "", "error");
}
});
and in my controller:
public function getBookTours(){
$record = $this->mdl->bookTours();
$this->output->set_output(json_encode($record));
}
and in my model:
public function bookTours(){
$info = array (
'total_price' => $this->input->post('fare'),
'total_distance_km' => $this->input->post('distance'),
'status' => 1,
'ip' => $this->getUserIP(),
'booked' => $time,
);
return $info;
}

Do you mean array of objects ?
[{'total_price':636 .....},{'total_price':8484....}]
Fisrt convert you array to JSON
var json = JSON.stringify(your_array);
Change the ajax to following
data: {data : json},
In the php
$data = json_decode($this->input->post("data"),true);
foreach($data as $obj){
//now you can access
echo $obj["total_price"];
}

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.

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
]);

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'];

Invalid argument supplied for foreach() when receive json

here is my code:
$.ajax({
type: "POST",
url: '<?php echo base_url();?>index.php/profile/add_jobs',
datatype: "json",
traditional: true,
data: {json:JSON.stringify(all_publication)},
success: function (response) {
console.log(response);
$('.all').html('');
}});return false; //disable refresh
and the all_publication is an array containing values,
in controller I put this code:
public function add_jobs()
{
echo ($_POST['json']);
foreach ($_POST['json'] as $key => $value) {
$data[] = array('name'=>$value['pub_name'],'details'=>$value['pub_details'],'date_time'=>$value['pub_date']);
}
$this->profile_model->insert_publication($data);
}
But appeared to me this message "Invalid argument supplied for foreach()"
please show me a way for my problem.
You don't need to stringify your array. Try:
data: {json : all_publication},
Use json_decode with second parameter as true (for getting output as array) before passing it to foreach loop
So revised code looks like
public function add_jobs()
{
echo ($_POST['json']);
$postArray=json_decode($_POST['json'], true); // Decoding json to array
foreach ($postArray as $key => $value) {
$data[] = array('name'=>$value['pub_name'],'details'=>$value['pub_details'],'date_time'=>$value['pub_date']);
}
$this->profile_model->insert_publication($data);
}

Sending array to controller/model in CI with AJAX

So basically I have a two item array in javascript that is generated based on which link the user clicks. I am trying to send this array to my controller, and then to the model. The model will look at the array and match one of the items to a certain column/row, and will selectively display data.
I am having issues passing the data from AJAX to my controller.
AJAX code (in a .js file)
$('#youmax-video-list-div').append('<div id="testing1"></div>');
$('#concept').click(function(){
console.log(course);
$.ajax({
url: 'http://localhost:8888/index.php/trial/getValues',
type:'POST',
dataType: 'json',
data:'',
error: function(){
$('#testing1').append('<p>goodbye world</p>');
},
success: function(result) {
var htmlStr = '';
$.each(result, function(a, b){
htmlStr += b.qText + '<br />';
});
$('#testing1').append(htmlStr);
} // End of success function of ajax form
}); // End of ajax call
});
I am assuming I must do something with the data field, but I dont know the syntax for it.
The console log in chrome comes up with this:
Array[2]
0: "PL8G0kdHFfE3WuyevUDvwSYCZw8mp8LBFA"
1: "PL8G0kdHFfE3V62Jp2ju-PelOaNUkH7xR8"
Controller
function getValues(){
$this->load->model('get_db');
$data = $this->get_db->getAll();
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode($data));
return $data;
}
Model
class Get_db extends CI_Model{
function getAll(){
$query=$this->db->query("SELECT * FROM questions");
return $query->result();
//returns from this string in the db, converts it into an array
}
}
As I said before, I am really only concerned with getting the data to my controller and my model.
The name of the array is "course". However, that doesnt appear to be so in the console.log. Is that just something chrome does?
// chkval be the class for elements for the arrays
AJAX function:
function ajaxSub(goals)
{
var theArray = new Array();
var i=0;
jQuery('.chkval').each(function(){
if(jQuery(this).prop('checked'))
{
theArray[i] = jQuery(this).val();
i++;
}
});
jQuery.ajax({
url: '<?php echo site_url('mycontroller/myfunctions');?>',
type: 'post',
data: {
arr: theArray,
other_id: ''
},
datatype: 'json',
success: function () {
}
});
}
in the controller:
$arr = $this->post('arr');
foreach($arr as $ar)
{
echo $ar; // prints each element of the array.
}
Same as above answer but in controller run this code:
$arr = $this->input->post('arr');
foreach($arr as $ar)
{
echo $ar; // prints each element of the array.
}

Resources