display data after selecting options from dropdown codeigniter - javascript

I'm very new here and also to codeigniter and Ajax.
I need to display data after selecting from the drop down option without reloading the page / submit button. It displays after the option is selected as I'm able to properly display data for the options, now I just need to display data based on that option on two separate fields.
For example :
paket : paket 1
description : its something something
jadwal : soon to be announced
the options are the product, the one I need to be displayed on their separate fields is the description on description field and jadwal on jadwal field.
Here is the code I have for the view:
//this is the code for the options
<div class="form-group">
<label for="paket">Pilih Paket</label>
<select class="form-control form-control-sm" name="paket" id="paket">
<option value="">Pilih Paket</option>
<?php
foreach ($datatour as $dttour)
{
if ($id==$dttour->id)
{
$s='selected';
}
else
{
$s='';
}
?>
<option <?php echo $s ?> value="<?php echo $dttour->id;?>"><?php echo $dttour->paket;?></option>
<?php
}
?>
</select>
</div>
<div class="row">
<div class="col-md-8" align="left">
<label for="jadwal">Jadwal</label>
<div style="border:1px solid #ccc;text-align:left;background-color:white;">
// this is where i display the jadwal data
</div>
</div>
</div>
<div class="kolom" style="border:1px solid #ccc;background-color:white;overflow:auto;" align="center">
<div class="row">
<h3>Detail Paket</h3> <br>
// this is where i display the description data
<p></p>
</div>
</div>
I haven't written any code for the models and the controllers, any help and explanation of the process (if that's not much to ask) would be very much appreciated, thank you.

Separate your view in two views:
First view: named sand_main.php in folder sandbox_v
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<div class="form-group">
<label for="paket">Pilih Paket</label>
<select class="form-control form-control-sm" name="paket" id="paket">
<option selected value="">Pilih Paket</option>
<option value="123">123</option>
<option value="324">566</option>
<option value="555">333</option>
<!-- I've used my own code, for checking the result, you should use your:
<option value="">Pilih Paket</option>
<?php
foreach ($datatour as $dttour)
{
if ($id==$dttour->id)
{
$s='selected';
}
else
{
$s='';
}
?>
<option <?php echo $s ?> value="<?php echo $dttour->id;?>"><?php echo $dttour->paket;?></option>
<?php
}
?>
-->
</select>
</div>
<div id="info"></div>
Where JS should be next:
<script type="text/javascript">
$(function(){
$('#paket').unbind('change');
$('#paket').change(function(){
var opt_sel = $('#paket').val();
$.ajax({
method:"POST",
url:'/index.php/sandbox/s1',
data:{
sel_op:opt_sel
}
}).done(function(a){
$('#info').html(a);
}).fail(function(){
alert("It's an epic fail.");
});
});
})
</script>
Second view: named sand_view_2.php in folder sandbox_v
<div class="row">
<div class="col-md-8" align="left">
<label for="jadwal">Jadwal</label>
<div style="border:1px solid #ccc;text-align:left;background-color:white;">
<?= $j_info; ?>
</div>
</div>
</div>
<div class="kolom" style="border:1px solid #ccc;background-color:white;overflow:auto;" align="center">
<div class="row">
<h3>Detail Paket</h3> <br>
<?= $d_info; ?>
<p></p>
</div>
</div>
Controller: in my example sandbox.php
<?php
class Sandbox extends CI_Controller {
public function __construct() {
parent::__construct();
}
public function index() {
// here you should get your $datatour data
$this->load->view('sandbox_v/sand_main.php', [
'datatour' => $datatour
]);
}
public function s1() {
$sel_val = $this->input->post('sel_op');
/*you can use your DB for getting a description for each value
* in this case you should add in __construct() your model as $this->load->model('your_model);
* or use your DB connection directly here.
*/
/* with your model:
* $jdwal_info = $this->your_model->your_jdwal($sel_val);
* $detail_info = $this->your_model->your_detail($sel_val);
*/
// without. It means that you've got info in the other way, for example, in predefined way:
if ($sel_val == 555) {
$jdwal_info = 'descr 1';
$detail_info = 'detail 1';
} else if ($sel_val == 123 ) {
$jdwal_info = 'descr 123';
$detail_info = 'detail 123';
} else if ($sel_val == 324 ) {
$jdwal_info = 'descr 324';
$detail_info = 'detail 324';
} else {
$jdwal_info = 'descr N\A';
$detail_info = 'detail N\A';
}
$this->load->view('sandbox_v/sand_view_2.php',[
'j_info' => $jdwal_info,
'd_info' => $detail_info
]);
}
}
Model: named your_model.php
<?php
class Your_model extends CI_Model {
function __construct()
{
$this->load->database();
}
public function your_jdwal($a) {
// process of getting result from DB over input variable $a (the name of it doesn't matter)
return $res;
}
public function your_detail($a) {
// process of getting result from DB over input variable $a (the name of it doesn't matter)
return $res;
}
}
Check it. It works for me.

Try to implement this code, reference in W3schools Jquery
$(document).ready(function(){
$("#btn_form_submit").click(function(){
$.ajax({
cache:false,
type:"POST"
//equivalent of action attribute in form tag
url:"path/to/your/php/"
data: $("my_form").serialize(),
success: function(data){
//returns data from php if success
}
});
});
});

Related

populate 2nd drop down based on 1st drop down result by using ajax in codeigniter php

I'm trying to do the 2nd drop down population based on the 1st drop down by using ajax in codeigniter. But my problem is after I choose for 1st drop down value, when I try to choose for 2nd drop down value, it shows empty only.
(Update: I already fixed my problem. So, I already updated my code.)
Image below shows that the result after I choose for 1st option. When I try to select for 2nd option, it can't shows the value:
Here's is the code for view:
<div class="container">
<div class="container h-100">
<div class="row h-100 justify-content-center align-items-center">
<div class="card">
<div class="card-body">
<h3 class="card-title text-center"><?php echo $content_heading;?></h3>
<form action="#" id="form" novalidate>
<div class="form-row">
<div class="col-sm-12">
<div class="form-group">
<label for="subject_name">Subject Name</label>
<select class="form-control" name="subject_name" id="subject_name">
<option>-- Select Subject Name --</option>
<?php foreach($attendance as $row){
echo "<option value='".$row['subject_id']."'>".$row['subject_name']."</option>";
}
?>
</select>
<div class="invalid-feedback"></div>
</div>
<div class="form-group">
<label for="lecturer_name">Lecturer Name</label>
<input name="lecturer_name" placeholder="Lecturer Name" class="form-control" type="text" disabled="">
<div class="invalid-feedback"></div>
</div>
<div class="form-group">
<label for="subject_section">Section</label>
<select class="form-control" name = "subject_section" id='subject_section'>
<option>-- Select Subject Section --</option>
</select>
<div class="invalid-feedback"></div>
</div>
<div class="form-group">
<label for="attendance_date">Date</label>
<input name="attendance_date" placeholder="Date" class="form-control" type="date">
<div class="invalid-feedback"></div>
</div>
<div class="form-group">
<label for="attendance_start_time">From</label>
<input name="attendance_start_time" placeholder="From" class="form-control" type="time">
<div class="invalid-feedback"></div>
</div>
<div class="form-group">
<label for="attendance_end_time">To</label>
<input name="attendance_end_time" placeholder="To" class="form-control" type="time">
<div class="invalid-feedback"></div>
</div>
<button type="button" id="btnSave" class="btn btn-primary btn-block" onclick="save()">Confirm</button>
</div>
</div>
</form>
</div>
</div>
</div>
Here is the javascript for the ajax function. (I already updated my javascript code.)
<script>
$(document).ready(function(){
// Subject change
$('#subject_name').change(function(){
var subject_id = $(this).val();
// AJAX request
$.ajax({
url : "<?php echo site_url('attendance/get_subject_section')?>",
method: 'POST',
data: {subject_id: subject_id},
dataType: 'JSON',
success: function(response){
// Remove options
$('#subjectsection').find('option').not(':first').remove();
// Add options
$.each(response,function(index,data){
$('#subject_section').append('<option value="'+data['subject_id']+'">'+data['subject_section']+'</option>');
});
}
});
});
});
</script>
Here is the code for controller:
<?php class attendance extends CI_Controller{
function __construct(){
parent::__construct();
$this->load->model('Attendance Data/attendance_model','attendance');
}
function index(){
//$this->load->view('Manage User Registration/user_login_view');
$data['meta_title'] = 'Attendance';
$data['content_heading'] = 'Attendance';
$data['main_content'] = 'Manage Student Attendance/attendance';
$data['user_id'] = $this->session->userdata('id');
if($this->session->userdata('user_type')==='lecturer'){
$data['user_type'] = 'lecturer';
$data['meta_user_level_title'] = 'Lecturer';
$data['id'] = $this->session->id;
$data['main_content'] = 'Manage Student Attendance/lecturer_attendance_view';
$this->load->view('template/template', $data);
}else{
echo "Access Denied";
}
}
public function create_attendance()
{
$data['meta_title'] = 'Add Subject Attendance';
$data['content_heading'] = 'Add Subject Attendance';
$data['main_content'] = 'Manage Student Attendance/attendance';
$data['user_id'] = $this->session->userdata('id');
$data['user_type'] = 'lecturer';
$data['heading'] = 'Lecturer';
if($this->session->userdata('user_type')==='lecturer'){
$data['user_type'] = 'lecturer';
$data['attendance'] = $this->attendance->get_subject_name();
$data['meta_user_level_title'] = 'Lecturer';
$data['id'] = $this->session->id;
$data['main_content'] = 'Manage Student Attendance/create_attendance';
$this->load->view('template/template', $data);
}else{
echo "Access Denied";
}
}
public function get_subject_section()
{
// POST data
$subject_id= $this->input->post('subject_id');
// get data
$data = $this->attendance->get_subject_section($subject_id);
echo json_encode($data);
}}
Here is my code for model:
<?php class attendance_model extends CI_Model{
//Get subject name
public function get_subject_name()
{
$user_id = $this->session->userdata("id");
$response = array();
// Select record
$this->db->select('*');
$this->db->where('lecturer_id', $user_id);
$this->db->group_by('subject_id');
$query = $this->db->get('lecturer_timetable');
$response = $query->result_array();
return $response;
}
//Get subject section
public function get_subject_section($subject_id){
$user_id = $this->session->userdata("id");
$response = array();
// Select record
$this->db->select('subject_id, subject_section');
$this->db->where('lecturer_id', $user_id);
$this->db->where('subject_id', $subject_id);
$query = $this->db->get('lecturer_timetable');
$response = $query->result_array();
return $response;
}}
Can someone help me to solve this problem? Thanks.
your url in ajax is unreadable because of quotation. Try to writer in proper quotation. Use either single quotes inside double quotes or use double inside single. Second is, you are using method as 'POST' but in lowercase. Write POST in uppercase.
$.ajax({
url : "<?php echo site_url('attendance/get_subject_section')?>",
method: 'POST',
data: {subject_name: subject_name},
dataType: 'json',
success: function(response){
console.log(response); // first check by console that you are getting records in response. once you get response then append it or do whatever you want
}
});

How to pass the id from url in php function without refreshing the page?

I have a div which contains a button(Book it).When I press the button I want to add to the current url the id of the item I clicked on.Then get that id to pop up a box with clicked item data without refreshing the page, because I need to pop up in the current page.
Here it gets the treatments Id
<div class="treatments">
<ul>
<?php
global $treatments;
foreach($treatments as $treatment){
echo ' <li>'.$treatment['name'].'</li>';
};
?>
</ul>
<div class="line"></div>
</div>
<div class="treatment-items">
<?php
global $iController;
$items;
if(isset($_GET['treatmentID'])){
$items = $iController->getItemByTreatmentId($_GET['treatmentID']);
}else{
$items = $iController->getItemByTreatmentId(4);
}
foreach($items as $item){
echo '
<div class="col-30 items">
<div>
<p>'.$item['id'].'</p>
<img src="'.$item['img_url'].'" alt="'.$item['name'].'" />
<h3>'.$item['name'].'</h3>
<p>'.$item['time'].' min</p>
<p>'.$item['price'].'$</p>
<input type="hidden" id="hidden_input" name="id_item" value="'.$item['id'].'">
<a class="bookBtn" id="btn"><button>BOOK IT</button></a> // when I press this button I want that box to pop up
</div>
</div>
';
}
?>
</div>
Pop up box
<div class="bookDetails">
<div class="details">
<?php
global $iController;
$itemm;
if(isset($_GET['id_item'])){
$itemm = $iController->getItemById($_GET['id_item']);
}
echo'
<h1>Book your treatment</h1>
<p>Treatment Name : '.$itemm['name'].'</p>
<p>Treatment Time :'.$itemm['time'].' </p>
<p>Treatment Price : '.$itemm['price'].'</p>
';
?>
<form action="" method="POST">
<label for="date">Choose your date:</label>
<input type="date" for="date" name="date"><br>
<input type="submit" value="Cancel" id="cancel">
<input type="submit" value="Book Now">
</form>
Jquery code
$(".bookBtn").click(function(){
$(".bookDetails").show();
})
getItemById function
public function getItemById($id){
$sql="SELECT * FROM treatments_item WHERE id=$id";
echo $id;
$items = mysqli_query($this->connection,$sql);
$returnArray = array();
if($items){
while($row = mysqli_fetch_assoc($items)){
array_push($returnArray, $row);
}
return $returnArray[0];
}else{
echo'It doesn't work';
}
}
You can use ajax or mix php and javascript like this:
<script>
$(document).ready(function() {
<?php session_start(); ?>//Remove session_start
if (!<?php $_GET(['id'])?'true':'false'; ?>) {
alert something
} else {
something ..
}
});
</script>
hope this was helpful. :)
<div class="treatment-items">
<?php
global $iController;
$items;
if(isset($_GET['treatmentID'])){
$items = $iController->getItemByTreatmentId($_GET['treatmentID']);
}else{
$items = $iController->getItemByTreatmentId(4);
}
foreach($items as $item){
echo '
<div class="col-30 items">
<div>
<p>'.$item['id'].'</p>
<img src="'.$item['img_url'].'" alt="'.$item['name'].'" />
<h3>'.$item['name'].'</h3>
<p>'.$item['time'].' min</p>
<p>'.$item['price'].'$</p>
<input type="hidden" class="id_item" value="'.$item['id'].'">
<div class="bookBtn"><button>BOOK IT</button></div> // when I press this button I want that box to pop up
</div>
</div>
';
}
?>
Note: Never use id same name in one Page i.e., id="hidden_input" // In for loop same name will be generated. It will create bug down the line. Same goes for Input name, instead use class.
$(document).ready(function(){
$('body').on('click','.bookBtn',function(){
var treatmentID = $(this).siblings('.id_item').val();
// $(this) --> it will read the data of the property you have clicked
// .siblings --> adjacent class with name ('.id_item')
$.ajax({
url: 'treatments.php',
type: "get", //send it through get method
data: {
treatmentID: treatmentID
},
success: function(response) {
//operation to show the data in div
//e.g., $('#divId').html(data.name);
$(".bookDetails").show();
}
});
})
})

How i get the values in select option using javascript

I am fetching acno from table when i select a party name in option.I have so far tired i get the acno from the table but it is not place in the option box.
My controller code:
public function get_states2()
{
$name = $this->input->post('name');
$result = $this->db->query("SELECT TAcNo FROM tipup_payment LEFT OUTER JOIN parmaster on parmaster.pcode = tipup_payment.TName WHERE PName='$name' ")->result_array();
echo json_encode($result);
}
My View page code:
<div class="col-md-6">
<div class="form-group form-group-xs">
<div class="col-lg-9">
Party Name:
<select class="form-control countries" name="City">
<option></option>
<?php foreach ($PName as $row ): ?>
<option value="<?php echo trim($row['PName']); ?>"><?php echo trim($row['PName']); ?></option><?php endforeach ?>
</select>
</div>
</div>
<div class="form-group form-group-xs">
<div class="col-lg-9">
AcNo:
<select multiple="multiple" style="height: 85px;" id="Name" class="form-control states">
<option value=""></option>
</select>
<?php echo form_error('Area', '<div class="text-danger">', '</div>'); ?>
</div>
</div>
<div id="item">
<input type="checkbox" name="item">With Details</center></div>
</div>
</div>
My Script Code:
<script type="text/javascript">
$(document).ready(function(){
$('.countries').change(function(){
var name = $('.countries').val();
$.ajax({
type: "POST",
url: "<?php echo base_url();?>Tieup/get_states2",
data:{name:name},
datatype: 'json',
success: function (data) {
/*get response as json */
alert(data);
var result = jQuery.parseJSON(data);
var no = result.TAcNo;
$("#Name").val(no);
/*ends */
}
});
});
});
</script>
This is my view page when i select a party name it should display the acno in acno option box( it down the party name).
give a class or id to ur dropdown
ur html
<select class="product">
</select>
ur jquery code
loop through all ur value and set it in ur option value one by one and at the end inject all ur html to ur select option using .html()
var value = [{"TAcNo":"341"}]
var options = '<option value="">Select</option>';
$(value).each((index, item) => { //loop through your elements
console.log(item)
options += '<option value="'+item.TAcNo+'">'+item.TAcNo+'</option>';
});
$('.product').html(options);
Hope it helps
Solution
you need to trigger change like this to update select value
$("#Name").val(no).change();

How to create repeatable fields in wordpress in my plugin setting page

This is my HTML code where I'm creating a simple HTML form in my plugin settings page:
<?php
/**
* Adds a submenu page under a custom post type parent.
*/
function books_register_ref_page()
{
add_submenu_page('edit.php?post_type=fscf_contact', __('Setting', 'fscf') , __('Settings', 'fscf') , 'manage_options', 'setting-fscf-contacts', 'fscf_contact_page_callback');
// call register settings function
add_action('admin_init', 'register_my_fscf_contact_settings');
}
function register_my_fscf_contact_settings()
{
// register our settings
register_setting('fscf-plugin-settings-group', 'fscf_field_1');
}
/**
* Display callback for the submenu page.
*/
function fscf_contact_page_callback()
{
?>
<div class="wrap">
<h1><?php
_e('Contact Form Setting', 'textdomain'); ?></h1> <hr>
<div class="wrap">
<form method="post" action="" id="myform">
<?php
settings_fields('fscf-plugin-settings-group'); ?>
<?php
do_settings_sections('fscf-plugin-settings-group'); ?>
<table class="form-table" id="p_scents">
<tr valign="top">
<th scope="row">New Option Name</th>
<td> <p>
<label for="p_scnts">
<input type="text" name="fscf_field_1" id="fscf_field_1" value="<?php
echo esc_attr(get_option('fscf_field_1')); ?>" /> <input type="button" id="addScnt" name="" value="+">
</label>
</p> </td>
</tr>
</table>
<?php
$other_attributes = array(
'id' => 'submit_repeatable_fields'
);
submit_button("Submit", "submit", "submit", false, $other_attributes); ?>
<span id="fscf_error"></span>
</form>
</div>
</div>
<?php
}
add_action('init', 'books_register_ref_page');
This is my .js code where I'm repeating <tr> in HTML form:
jQuery(document).ready(function() {
var scntDiv = jQuery('#p_scents');
var i = jQuery('#p_scents p').size() + 1;
jQuery('#addScnt').live('click', function() {
jQuery('<tr valign="top"><th scope="row">New Option Name</th><td> <p><label for="p_scnts"><input type="text" name="fscf_field_' + i +'" id="fscf_field_' + i +'" value="" /> Remove</p> </td></tr>').appendTo(scntDiv);
i++;
return false;
});
jQuery('#remScnt').live('click', function() {
if( i > 2 ) {
jQuery(this).parents('#p_scents tr').remove();
i--;
}
return false;
});
// Making Ajax Request for settings
jQuery("#myform").submit(function(e) {
e.preventDefault();
var formdata = jQuery("#myform input[type='text']").serializeArray();
var numberflds = jQuery("#myform input[type='text']").size();
var data = {
'action' : 'fscf_create_repeatable_fields',
'fullform':jQuery("#myform input[type='text']").serializeArray(),
'fields': numberflds,
//nonce : security
};
// We can also pass the url value separately from ajaxurl for front end AJAX implementations
jQuery.post(ajax_obj.ajax_url, data, function(response) {
console.log(response);
jQuery("#fscf_error").html(response);
});
});
});
Here is my php code where I want to save fields which I had repeated in .js file but I'm unable to save data:
function fscf_create_repeatable_fields(){
$mydata = $_POST['fullform'];
$fields = $_POST['fields'];
//$i=0;
foreach ($_POST['fullform'] as $form) {
register_setting( 'fscf-plugin-settings-group', $form['name']);
//$i++;
}
echo "Field Created.";
wp_die();
}
add_action( 'wp_ajax_nopriv_fscf_create_repeatable_fields', 'fscf_create_repeatable_fields' );
add_action( 'wp_ajax_fscf_create_repeatable_fields', 'fscf_create_repeatable_fields' );
So, the problem is I can't save repeatable fields in my plugin page. What mistake I'm doing?

jQuery on change dropdown call web service to load options

I have a form with a dropdown list and a variable amount of options (in the form of checkboxes and text inputs).
What I want to achieve is onchange value of the dropdown list, call a web service and load the various options below it. I know roughly I have to use jQuery's onchange event and have Ajax load the markup into the div.
But how exactly do I achieve that?
I am using Bootstrap 3, and some of my form code is below. I am not sure how to write my Javascript or Ajax part, though.
Dropdown list
<div class="form-group">
<label for="inputBranch" class="col-lg-2 control-label">Branch</label>
<div class="col-lg-10">
<select class="form-control" id="resBranch">
<?php
// print all branch name
// if is same as merchantID, mark as selected
foreach($branchesArray as $branch) {
if($branch['merchantID'] == $merchantID) {
echo "<option selected>" . $branch['name'] . "</option>";
} else {
echo "<option>" . $branch['name'] . "</option>";
}
}
?>
</select>
</div>
</div>
Options
<div class="form-group">
<label for="" class="col-lg-2 control-label">Options</label>
<div class="col-lg-10">
<?php
foreach ($featuresArray as $feature) {
?>
<div class="checkbox">
<label>
<input type="checkbox" value="<?php echo $feature['customValue']; ?>">
<?php echo $feature['customValue']; ?>
</label>
</div>
<?php
} // end foreach
?>
</div>
</div>
You could send an ajax request with the currently selected form option to a php web service which returns the html to add to the form.
The js could look something like this:
$( document ).ready(function () {
$('select').change(function () {
$.get('ajax.php?option=' + $('select').val(), function(data) {
if(data == "error")
{
//handle error
}
else {
$('div.ajax-form').append(data); //create an element where you want to add
//this data
}
});
});
});
The php might look like this:
if(isset($_GET['option'])) {
if($_GET['option'] == 1)
{
//echo form data for option one here
}
elseif($_GET['option'] == 2)
{
//echo form options for option two here
}
elseif($_GET['option'] == 3)
{
//echo form options for option two here
}
//other options here
else
{
echo "error"; //select value not correct
}
}

Categories