How to pass data to controller to view using json in php? - php

I using codeigniter.I need to pass data to my controller to view somehow.I manage to pass view to controller(in view when drop-down selected value pass to controller using ajax)
this is my HTML code
<div class="form-group">
<label for="lastname" class="control-label">Your Packages</label>
<?php if(isset($tourbuddy_packages)){?>
<select id="itemType_id" class="form-control input-sm" name="tripbuddy_PackageTitle" onChange="disp_text()">
<?php
foreach ($tourbuddy_packages as $packages) {?>
<option value="<?php echo $packages['PackageID'] ?>"><?php echo $packages['PackageTitle']?></option>
<?php } ?>
</select>
<input type="hidden" name="PackageID" id="country_hidden">
<?php } else { ?>
<select class="form-control input-sm" name="tripbuddy_PackageTitle">
<option>Add Packages</option>
</select>
<?php } ?>
</div>
when drop-down selected a vale i pass data to controller by using ajax and java Script
$("#itemType_id").change(function() {
$.ajax({
url : "feature/tea/",
method: "POST",
data: "id=" + $(this).val(),
success: function(response) {
// handle
}
})
});
Selected vale pass to tea method in controller
public function tea()
{
$this->session->set_userdata(array('tripbuddy_PackageID'=>$_POST['id']));
$package_data = $this->ci->package_model->get_package($_POST['id']);
$package_cat = $this->ci->package_model->get_package_categories();
$data = array();
$data['tourbuddy_selected_package'] = $package_data[0];
$data['tourbuddy_selected_package_cat'] = $package_cat;
//echo $data['package']['AlbumID'];
$data['tourbuddy_selected_photos'] = $this->photo->get_package_photo_stream($data['tourbuddy_selected_package']['AlbumID']);
//echo var_dump($data['photos']);
echo json_encode($data);
}
now I need to pass $data array to my view without refreshing view page how can i do this ? need a quick help

First you need to add the correct header to your tea() function as it will be returning json
public function tea()
{
header('Content-Type: application/json');
//...
}
Then you will need to add the dataType parameter to your ajax call
$("#itemType_id").change(function() {
$.ajax({
url : "feature/tea/",
method: "POST",
dataType: 'json', //Added this
data: "id=" + $(this).val(),
success: function(response) {
// handle
}
})
});
In your success function you will then be able to access the data like
success: function(response) {
response.tourbuddy_selected_photos.data
}

Controller
class Feature extends CI_Controller
{
public function tea()
{
$post = $this->input->post(); //do some form validation here
$model = Model::get($post); // do all business logic in the model
if(!$model){
//return a Response header rather than a 404View
return $this->output->set_status_header(404);
}
$responce = array(
'something' => $model->something
);
return $this->output
->set_content_type('application/json')
->set_output(json_encode($responce))
->set_status_header(200);
}
}
Untested Javascript
var URL = <?php echo site_url(); ?>// Global URL variable
(function($){
var Form = {
init : function(){
this.Form = $("form#formId"),
this.ItemType = this.Form.find("#itemtype_id");
this.ItemType.on('change', $.proxy(this.change, this));
},
/**
* -----------------------------------------------------------------
* Bind the ItemTypeId change event to this function using $.proxy
* Ajax return's a deffered(promise) so capture it, and do stuff
* -----------------------------------------------------------------
**/
change : function(event){
this.doAjax(event.target).then(
function( data ) // success
{
$(this).html('Success'); // $(this) -> context
},
function( reason ) //fail
{
switch(reason.code)
{
case 404:
default:
$(this).html('no results found');
break;
}
}
);
},
/**
* -----------------------------------------------------------------
* Make the ajax request a wait for it to return a promise
* -----------------------------------------------------------------
**/
doAjax : function( target ){
var data = {
id : target.id
}
return $.ajax({
cache: false,
url : URL + 'feature/tea/',
context : target,
method: "POST",
data : data,
dataType : 'json',
}).promise();
}
}
Form.init();
}(jQuery));

Related

How to send dropdown selected value through ajax call to controller in laravel

I'm new with laravel and I want to send the selected dropdown option value of product name through ajax data to the controller
For Example: If I'm select 1st plastic product option value from a drop-down then in the controller from request object I want that selected product name
as per my below code I'm getting null in the request object of the product name
Here is my route:
Route::get('product', 'ProductController#index')->name('product');
Here is my controller:
public function index(Request $request)
{
if (isset($request->productName)) {
$productName = $request->productName;
dump($productName); // getting null
} else {
$productName = null;
}
return view('Product.product');
}
Here is my an ajax call:
function display(productName){
productName = $('#product_filter').val(); // Here, I'm getting selected value of dropdown
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: "{{route('product')}}",
type: "GET",
data:{
'productName' : productName // in header request I'm getting value [productName: plastic product] *
},
success:function(data){
console.log(data);
},
error:function(e){
console.log(e,'error');
}
});
}
header request result
I don't know if I'm doing something wrong,
ends with wanting to get help from helping hands please help me to get the selected value to the controller object
I believe you got null because you are returning a full HTML to the Ajax request. In order to get the payload sent from the Ajax, you have to return a JSON response like this:
public function index(Request $request)
{
$productName = null;
if (isset($request->productName)) {
$productName = $request->productName;
}
return response()->json($productName);
}
That being said, I'm unable to reproduce the issue without seeing how do you call the method and where would you show the data to. And I assume you want to simply just do a console.log(data) like you did on the given snippet. In this case, the snippet above will work.
And if you want to keep the view to prevent error when you refresh the page, just add a new method for that specific call in your controller and send the request to that endpoint, like this:
web.php
<?php
Route::get('/', [ProductController::class, 'index']);
Route::get('/productFilter', [ProductController::class, 'productFilter'])->name('dashboard-product-data');
ProductController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ProductController extends Controller
{
public function index(Request $request)
{
return view('welcome');
}
public function productFilter(Request $request)
{
$productName = null;
if (isset($request->productName)) {
$productName = $request->productName;
}
return response()->json($productName);
}
}
welcome.blade.php
<div>Product Name: <span id="product-name"></span></div>
<select id="product_filter" name="product_filter">
<option value="plastic product">plastic product</option>
</select>
<button id="submit-button" type="button">Send data</button>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script>
function display(productName){
productName = $('#product_filter').val(); // Here, I'm getting selected value of dropdown
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: "{{route('dashboard-product-data')}}",
type: "GET",
data:{
'productName' : productName // in header request I'm getting value [productName: plastic product] *
},
success:function(data){
console.log(data);
document.querySelector('#product-name').innerHTML = data
},
error:function(e){
console.log(e,'error');
}
});
}
const submitButton = document.querySelector('#submit-button')
submitButton.addEventListener('click', () => display())
</script>

Dependable drop down list using ajax in codeigniter is not working

Im trying to make a dependable dropdownlist using ajax in codeigniter. I used a code..but its not working.. the values are not appended to the dropdownlist. Retrieving data from database to first dropdown list is working perfectly. First Dropdown list works fine...but i want to make dependable dropdown list subcategory based on category using ajax
CONTROLLER::
public function pdview()
{
$this->load->helper('url');
$this->load->helper('form');
$this->load->model('AjaxpModel');
$data['cnames'] = $this->AjaxpModel->getcat();
$this->load->view('pd',$data);
}
public function getsubcaty()
{
$postData = $this->input->post();
$this->load->model('AjaxpModel');
$data = $this->AjaxpModel->getsubcategory($postData);
echo json_encode($data);
}
View::
Category Name : <select name="category" id="category">
<option value="">Select</option>
<?php
foreach($cnames as $catn){
echo "<option value='".$catn['catname']."'>".$catn['catname']."</option>";
}
?>
</select><br><br>
Subategory Name :
<select name="subcategory" id="subcategory">
<option value="">Select</option>
</select><br><br>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type='text/javascript'>
var baseURL= "<?php echo base_url();?>";
$(document).ready(function(){
// Category Change
$('#category').change(function(){
var cat = $(this).val();
// AJAX request
$.ajax({
url:'<?=base_url()?>index.php/Ajaxuser/getsubcaty',
method: 'post',
data: {cat:cat},
dataType: 'json',
success: function(response){
$('#subcategory').find('option').not(':first').remove();
// Add options
$.each(response,function(index,data){
$('#subcategory').append('<option value="'+data['subcatname']+'">'+data['subcatname']+'</option>');
});
}
});
});
});
Model:::
public function getcat()
{
$this->load->database();
$result=$this->db->select('cid,catname')->from('catc')->get()->result_array();
$cname=array();
foreach($result as $r)
{
$catname[$r['catname']] = $r['catname'];
}
$catname[''] = 'Select ';
return $catname;
}
function getsubcategory($postData){
$response = array();
// Select record
$this->db->select('scid,subcatname');
$this->db->from('scatc');
$this->db->where('catname', $postData['cat']);
$q = $this->db->get();
$response = $q->result_array();
return $response;
}
first of all check if your base_url() is defined properly.
As you followed my steps on comment section, I think I see the issue on your JS,
You can try this one:
$(document).ready(function(){
// Category Change
$('#category').change(function(){
var cat = $(this).val();
// AJAX request
$.ajax({
url:'<?=base_url()?>index.php/Ajaxuser/getsubcaty',
method: 'post',
data: {cat:cat},
dataType: 'json',
success: function(response){
var $el = $("#subcategory");
$el.empty();
$("#subcategory").val('');
$el.append($("<option></option>")
.attr("value", '')
.attr("hidden",'')
.text('Select Subcategory'));
$.each(response, function(index, data){
$el.append('<option
value="'+data.subcatname+'">'+data.subcatname+'</option>')
});
}
});
});
});
Let's see what you got there after trying this.
On your getsubcategory model you forgot to load the database. It should be like this:
$this->load->database();
On same model function, $postData[cat] must be only $postData because you are not passing an array data from your controller otherwise you will be having Illegal string offset error.
EDIT:
Since we've figured out that the problem is base_url()
Configure if the helper 'url' is loaded, you can set it on application/config/autoload.php.
and you must define it to know what exactly the value of base_url().
You can set it on application/config/config.php.
To test if the base_url() is working, try to echo base_url().

Queing notification in PHP using AJAX with beep sound

I am building now a Queuing system for my helpdesk system. i have problem in detecting the changes of input value. I want to play the play_sound() function sound when the value of input is incremented. the curent value of input is coming from the rowCount in my SQL Query stored in variable.
screenshot picture link
Input
<input disabled type="text" id="needapproval" id="approval" value="0" class="center" />
My Script
<script type="text/javascript">
function play_sound() {
var audioElement = document.createElement('audio');
audioElement.setAttribute('src', 'Kalimba.mp3');
audioElement.setAttribute('autoplay', 'autoplay');
audioElement.load();
audioElement.play();
}
activateMagic();
function activateMagic() {
setInterval(realTimeData, 1000);
function realTimeData() {
$.ajax({
url: './includes/needapproval.php',
method: 'GET',
dataType: "json",
success: function(res) {
$("#needapproval").val(res.data_count);
},
error: function(err) {
console.log(err);
}
});
}
}
</script>
PHP
require_once "connection.php";
class NeedApprovalStatus extends Connection{
public function needApproval() {
$count_approval = "SELECT * FROM job_request WHERE approval_status LIKE '%Need Approval%' ";
$stmt_count_approval = $this->db->prepare($count_approval);
$stmt_count_approval->execute();
$count = $stmt_count_approval->rowCount();
$data_count = [];
if ($count == 0) {
$data_count = [
'data_count' => 0
];
} else {
$data_count = [
'data_count' => $count
];
}
echo json_encode($data_count);
}
}
$need_approval = new NeedApprovalStatus;
$need_approval->needApproval();
I tried to use onchange event in jquery but it doesn't work. because i think onchange only trigger when you change value on input manually. Any ideas guys?
It would be easier to check the value inside the success function and call play_sound() from there.
function activateMagic() {
var value = 0;
setInterval(realTimeData, 1000);
function realTimeData() {
$.ajax({
url: './includes/needapproval.php',
method: 'GET',
dataType: "json",
success: function(res) {
var newValue = res.data_count;
if(newValue != value) {
play_sound()
$("#needapproval").val(value);
value = newValue;
}
}
...

Display ajax posted array in codeigniter view

I need to display objects of an array in a view that has been posted to controller from another view.
Jquery ajax call
details is an array with few objects
$(document).ready(function () { // working
$("#nxt").click(function() {
var tmp = details;
var more_details = JSON.stringify(tmp);
$.ajax({
type: "POST",
url: 'http://localhost/application/index.php/Welcome/detailsLoad',
data: {more_details : more_details },
success : function(){
console.log('Posted');
location.href="http://localhost/application/index.php/Welcome/detailsLoad"
},
error: function(){
alert('Error!');
}
});
});
});
Controller
public function detailsLoad()
{
$moreDetails= $this->input->post('more_details');
$this->load->view('simulation',$moreDetails);
}
View
<?php
foreach($moreDetails['more_details'] as $result) {
echo $result['object1'], '<br>';
echo $result['object2'], '<br>';
}
?>
help me to modify and fix this code
If you want to data from the ajax call to move from your controller to your view you should set the name of the variable to be used inside your view:
$data = [];
$data['moreDetails'] = $this->input->post('more_details');
$this->load->view('simulation',$data);
Then you can use the variable $moreDetails inside the view:
foreach ($moreDetails as $result) {
echo $result['object1'], '<br>';
echo $result['object2'], '<br>';
}

autocomplete value in textbox codeigniter

I have done to make control autocomplete, but I have a problem to post data with jquery.
<input type="text" id="matakuliah" class="med" name="matakuliah">
<script type="text/javascript">
$(this).ready( function() {
$("#matakuliah").autocomplete({
minLength: 1,
source:
function(req, add){
$.ajax({
url: "<?php echo site_url('bahanAjar/lookup'); ?>",
dataType: 'json',
type: 'POST',
data:req,
success:
function(data){
if(data.response =="true"){
add(data.message);
}
},
});
},
});
});
</script>
on my controller
function lookup(){
// process posted form data (the requested items like province)
$keyword = $this->input->post('term');
$data['response'] = 'false'; //Set default response
$query = $this->matakuliah_model->lookup($keyword); //Search DB
if( ! empty($query) )
{
$data['response'] = 'true'; //Set response
$data['message'] = array(); //Create array
foreach( $query as $row )
{
$data['message'][] = array(
'id_matakuliah'=>$row->id,
'value' => $row->matakuliah,
''
); //Add a row to array
}
}
if('IS_AJAX')
{
echo json_encode($data); //echo json string if ajax request
}
else
{
$this->load->view('admin/bahan_ajar/form_manage_file_view', $data); //Load html view of search results
}
}
The code work it well, but I want to add parameter to call database.
$query = $this->matakuliah_model->lookup($keyword, $id_matakuliah);
like this. how I can get
$this->input-<post('id_matakuliah')
from jquery before.;
and I have another textbox for fill value of autocomplete from textbox matakuliah.
`<input type="hidden" id="matakuliah_post" class="med" name="matakuliah_post">`
When I'm use autocomplete textbox automatic fill another textbox, please help me.
In this case req will contain {term:"your search term"}. Your can extend this javascript object to pass extra data. If you want to post id_matakuliah, you can assign its value like following before $.ajax call:
req.id_matakuliah = "Whatever you want to send";

Categories