Auto populate based on dropdown selected, need help - php

How can I auto populate the data from db by dropdown selected?
and my dropdown result already appear as well, the code as following:
<?php
echo '<tr>
<td>'.$customer.'</td>
<td><select name="customer_id">';
foreach ($customers as $customer) {
if ($customer['customer_id'] == $customer_id) {
echo '<option value="'.$customer['customer_id'].'" selected="selected">'.$customer['name'].'</option>';
} else {
echo '<option value="'.$customer['customer_id'].'">'.$customer['name'].'</option>';
}
}
echo '</select>
</td>
</tr>';
?>
and the result of dropdown above listed as
admin
customer1
FREE
loaded from following db
INSERT INTO `my_customer` (`customer_id`, `name`, `firstname`, `lastname`) VALUES
(8, 'admin', '', ''),
(6, 'customer1', 'ok', ''),
(7, 'FREE', 'marj', 'om');
so whenever dropdown selected i want the all data below:
<tr>
<td><?php echo $firstname; ?></td>
<td><?php echo $lastname; ?></td>
</tr>
also auto populate, it seem need javascript/ajax/jquery to fixed it, I was Wondering if someone could help me, and thanks in advance
Addtion JSON CALL
I have the json call already as following:
(let say this placed at customer.php with url index.php?p=page/customer)
public function customers() {
$this->load->model('account/customer');
if (isset($this->request->get['customer_id'])) {
$customer_id = $this->request->get['customer_id'];
} else {
$customer_id = 0;
}
$customer_data = array();
$results = $this->account_customer->getCustomer($customer_id);
foreach ($results as $result) {
$customer_data[] = array(
'customer_id' => $result['customer_id'],
'name' => $result['name'],
'firstname' => $result['firstname'],
'lastname' => $result['lastname']
);
}
$this->load->library('json');
$this->response->setOutput(Json::encode($customer_data));
}
and the db
public function getCustomer($customer_id) {
$query = $this->db->query("SELECT DISTINCT * FROM " . DB_PREFIX . "customer WHERE customer_id = '" . (int)$customer_id . "'");
return $query->row;
}

Suppose You are using jQuery, You will listen to select change event and then do an ajax call for PHP function that will return the data. The data will then be outputed to the appropriate places. I advise to set id attributes for next tags: <select>, <td> for name, <td> for surname, like so:
<select name="customer_id" id="customer_id>...</select>
<td id="firstname"> echo firstname </td>
<td id="lastname"> echo lastname </td>
Then the jquery code:
<script type="text/javascript">//<!--
$(document).ready(function(){
$('select#customer_id').change(function(){
$.post(
"http://www.domain.com/my_php_script.php",
{customer_id: $(this).val()},
function(data){
$('td#firstname').html(data.firstname);
$('td#lastname').html(data.lastname);
}
);
});
});
//--></script>
Supposing that Your my_php_script.php retrieves the data from database by given customer_id in $_POST['customer_id'] and returns a JSON object like echo json_encode(array('firstname' => FIRSTNAME_FROM_QUERY, 'lastname' => LASTNAME_FROM_QUERY));
ADDITION:
There are two options how to solve it - in JS instead of
$.post()
You have to use
$.get(...)
OR in Your PHP script instead of
$this->request->get['customer_id']
You have to use
$this->request->post['customer_id']
at every place... This should do it...
E.g.:
<script type="text/javascript">//<!--
$(document).ready(function(){
$('select#customer_id').change(function(){
$.get(
"http://www.domain.com/my_php_script.php",
{customer_id: $(this).val()},
function(data){
$('td#firstname').html(data.firstname);
$('td#lastname').html(data.lastname);
}
);
});
});
//--></script>

Related

CodeIgniter: Trying to load the option values from database table based on the selection of first select option

I am using CodeIgniter and have a form with 2 select options. First select options is the Car Make and the second select option is the Make. If I select the Car Make from the As 'BMW' the Values in the second select options should change and show all the Models Made by BMW.
**WelcometoDemoCar.php (View)**
*//to get the Car Make List Box*
<input type = "text" name = "car_list" list="car_dalalist" id = "car_list" class = "inktext inklarge" placeholder = "Type of Car" required = "" autocomplete="off" />
<datalist id="car_dalalist">
<?php foreach($carlist as $row_carlist){?>
<?php //echo $row_carlist->Make . " " .$row_carlist->Model ." " .$row_carlist->Year ;?>
<option value="<?php echo $row_carlist->Make;?>"> <?php echo $row_carlist->Make;?></option>
<?php }?>
</datalist>
*//to get the value in the Make Select List Box*
<input type = "text" name = "car_model" list="car_model_dalalist" id = "car_model" class = "inktext inklarge" placeholder = "Car Model" required = <datalist id="car_model_dalalist">
<?php foreach($carModel as $row_carModel){?>
<?php //echo $row_carlist->Make . " " .$row_carlist->Model ." " .$row_carlist->Year ;?>
<option value="<?php echo $row_carModel->Model;?>"><?php echo $row_carModel->Model;?> </option>
<?php }?>
</datalist>
**Welcome.php (Controller)**
$this->data['carlist'] = $this->PostModel->getCarDetails();
$this->data['carModel'] = $this->PostModel->getCarModel();
**PostModel.php (Model)**
*//to get car make*
function getCarDetails(){
$this->db->Distinct();
$this->db->select("Make");
$this->db->from('carlist');
$carListquery = $this->db->get();
return $carListquery->result();
}
*// to get car model*
function getCarModel(){
$make = $this->input->post('car_list');
$this->db->Distinct();
$this->db->select("Model");
$this->db->from('carlist');
$this->db->where('Make' . $make);
$carmodelquery = $this->db->get();
return $carmodelquery->result();
}
public function get_data()
{
$value = $this->input->post("value");
$data = $this->PostModel->get_data($value);
$option ="";
foreach($data as $d)
{
$option .= "<option value='".$d->id."' >".$d->Model."</option>";
}
echo $option;
}
I tried few solutions posted on various sites using ajax, but I think my values are not getting posted to the controller.
ajax code
$("#car_list").on("change",function(){
var value = $(this).val();
$.ajax({ url : "welcome/get_data",
type: "post",
data: {"value":'value'},
success : function(data){
$("#car_model").html(data);
},
});
});
Really appreciate your time and help.
Thank in advance.
There were a couple of issues regarding the code.
For future reference: see the comments on the OP's post
Main issue was with the click handler:
$("#car_list").on("change",function(){
var value = $(this).val();
$.ajax({ url : "welcome/get_data",
type: "post",
data: {"value":value}, //OP originally used single quotes on the value therefore passing a string instead of the actualy variable
success : function(data){
$("#car_model").html(data);
},
});
});
Issues with the controller and model
public function get_data()
{
$data = $this->PostModel->get_data(); //OP originally passed $value to the model but $value does not exist
$option ="";
if(count($data) > 0){
foreach($data as $d)
{
$option .= "<option value='".$d->Model."' >".$d->Model."</option>";
}
echo $option;
}
}
Please update data: {"value":'value'}, with data: {"value":value}
( Remove single quotes from value )

Passing selected checkbox from array data into database with Codeigniter

i'm newbie for codeigniter. i trying to passing data attendance into database.
this my view code
<?php $no=1; foreach($employee AS $list_emp) { ?>
<tr>
<td><?= $no ?></td>
<td><input type="hidden" name="employee[]" value="<?php echo $list_emp->sn; ?>"><?= $list_emp->name; ?></td>
<td><?= $list_emp->position; ?></td>
<?php foreach ($attend_detail AS $list) {?>
<td><input type="checkbox" name="detail[]" value="<?php echo $list['details']"></td>
<?php } ?>
<td><input type="text" name="note[]"></td>
<input type="hidden" name="location[]" value="<?php echo $list_emp->branch; ?>">
</tr>
<?php $no++;} ?>
when i checked for 1 employee attendance (example 4630 is work), data can pass to database, but result like this (see image 2)
all data view input to database, not data when 1 checked before and remark WORK insert into row 1.
this my controller
function add_attend()
{
$employee = $this->input->post('employee');
$location = $this->input->post('location');
$detail = $this->input->post('detail');
$note = $this->input->post('note');
$total = count($employee);
if (empty($detail) === true) { $errors['detail'] = 'please select one';}
if (!empty($errors)){
$info['success'] = false;
$info['errors'] = $errors;
}
else {
for ($x=0; $x<$total; $x++){
$data = array(
'sn' => $employee[$x],
'lab' => $location[$x],
'stat' => $detail[$x],
'note' => $note[$x]
);
$this->m_human_capital->insert_attend($data);
}
$info['success'] = true;
}
$this->output->set_content_type('application/json')->set_output(json_encode($info));
}
and this my model
function insert_attend($data)
{
$this->db->insert('tb_attend_tes',$data);
}
i just want insert employee attendance who i checked. please help
thanks for anyone help.
sorry my bad english
Add an identifier on your employee attendance input name, so each employee have their own unique attendance dataset.
view :
...
<td><input type="checkbox" name="detail[<?php echo $no-1 ?>][]" value="<?php echo $list['details']"></td>
...
Since the attendance input is a multidimensional array, for the empty validation, you could use array_filter to check the whole attendance array.
And because of you are inserting an array data type into a single column, you need to concatenate it, you could use implode() function.
controller :
function add_attend()
{
$employee = $this->input->post('employee');
$location = $this->input->post('location');
$detail = $this->input->post('detail');
$note = $this->input->post('note');
$total = count($employee);
$filtered_detail = array_filter($detail);
if (empty($filtered_detail) === true) {
$errors['detail'] = 'please select one';
}
if (!empty($errors)){
$info['success'] = false;
$info['errors'] = $errors;
}
else {
for ($x=0; $x<$total; $x++){
$data = array(
'sn' => $employee[$x],
'lab' => $location[$x],
'stat' => (isset($detail[$x]) && !empty($detail[$x])) ? implode(",",$detail[$x]) : '',
'note' => $note[$x]
);
$this->m_human_capital->insert_attend($data);
}
$info['success'] = true;
}
$this->output->set_content_type('application/json')->set_output(json_encode($info));
}

Codeigniter - How to create a form with undefined number of input?

So I've been trying to create an 'add' function for a contest table that is also linked to a joining table as the contest has many sport events associated to it (and a sport events will also be included in many contests). I have managed to create it as below, however it is limited to only adding one row into the joining table based on the chosen game in a dropdown.
So now, how do I go about creating the form if I don't know how many sport events there might be? How will the website create another dropdown if one dropdown is used so that more sport events can be selected? Similarly, how does the controller know that there are x amount of dropdowns selected, and hence x amount of rows to be added to the joining table?
I'm sorry if I am using incorrect or ambiguous terms to describe my problem. I have only started learning and creating websites recently.
Thank you.
UPDATE: I may have a solution per the updated codes below. However I am now stuck on the inserting into the database page. For some reason when I click submit, the next page loads but with no error and no rows inserted. Please help :)
View
<h1>Add New Contest</h1>
<?php
echo form_open('contests/add/');
?>
<?php
echo "<br />" "<br />"
echo "Contest Name";
$data = array( 'name' => 'contest_name',
'value' => set_value('contest_name'),
);
echo form_input($data);
echo "<br />" "<br />"
echo "Game";
?>
<div class="field_wrapper">
<div>
<select name="field_name[]">
<option value="" disabled selected>Select Game</option>
<?php
foreach($events_lists->result() as $row) {
$sports_events_id = $row->sports_events_id;
$sports_events_start_date = $row->sports_events_start_date;
$sports_events_start_time = $row->sports_events_start_time;
$home_team_shorthand = $row->home_team_shorthand;
$away_team_shorthand = $row->away_team_shorthand;
?>
<option value="<?php echo $sports_events_id; ?>"><?php echo $home_team_shorthand; ?> v <?php echo $away_team_shorthand; ?> - <?php echo $sports_events_start_date; ?> <?php echo $sports_events_start_time; ?></option>
<?php } ?>
</select>
<img src="add-icon.png"/>
</div>
</div>
<?php
echo "<br />" "<br />"
$data = array( 'value' => 'Add Contest',
'name' => 'submit',
'class' => 'submit-btn',
);
echo form_submit($data);
echo form_close();
?>
Controller
function add()
{
$league_id = $this->uri->segment(3);
$this->load->module('leagues');
$data['leagues_list'] = $this->leagues->get_where($league_id);
foreach ($data['leagues_list']->result() as $row) {
$league_insert_id = $row->id;
$this->load->module('sports_events');
$data['events_lists'] = $this->sports_events->get_events_list($league_insert_id);
}
if ($this->form_validation->run() == FALSE) {
$data['view_file'] = 'add_contest';
$this->load->module('template');
$this->template->cmslayout($data);
} else {
$data1 = array(
'contest_name' => $this->input->post('contest_name')
);
if(isset($_REQUEST['submit'])) {
$data2 = $_REQUEST['field_name'];
}
if ($this->_transactions_new_contest($data1, $data2)) {
return $query;
$this->session->set_flashdata('team_phase_created', 'The team phase has been set');
redirect('/contests/');
}
}
}
Model
function _transactions_new_contest($data1, $data2){
$this->db->trans_start();
$this->db->insert('contests', $data1);
$contest_id = $this->db->query('SELECT contests.id FROM contests ORDER BY contests.id DESC limit 1');
foreach ($contest_id->result() as $row) {
$contest_result_id = $row->id;
foreach($data2 as $value){
$this->db->query('INSERT INTO contests_has_sports_events (contests_id, sports_events_id) VALUES (' . $contest_result_id . ', ' . $value . ')');
} }
$this->db->trans_complete();
}

How to make auto complete form in cakephp?

I am trying to make an auto complete function in CakePHP but did not succeed. I tried the following code.
public function find() {
if ($this->request->is('ajax')) {
$this->autoRender = false;
$country_name = $this->request->data['Country']['name'];
$results = $this->Country->find('all', array(
'conditions' => array('Country.name LIKE ' => '%' . $country_name . '%'),
'recursive' => -1
));
foreach($results as $result) {
echo $result['Country']['name'] . "\n";
}
echo json_encode($results);
}
}
// Form and jquery
<?php
echo $this->Form->create('Country', array('action' => 'find'));
echo $this->Form->input('name',array('id' => 'Autocomplete'));
echo $this->Form->submit();
echo $this->Form->end();
?>
<script type="text/javascript">
$(document).ready(function($){
$('#Autocomplete').autocomplete({
source:'/countries/find',
minLength:2
});
});
</script>
foreach($results as $result) {
echo $result['Country']['name'] . "\n";
}
Breaks your JSON structure.
Keep in mind that autocomplete by default expects "label" and value keys in your JSON table, so all the script should do after fetching DB records is:
$resultArr = array();
foreach($results as $result) {
$resultArr[] = array('label' =>$result['Country']['name'] , 'value' => $result['Country']['name'] );
}
echo json_encode($resultArr);
exit(); // may not be necessary, just make sure the view is not rendered
Also, I would create the URL to your datasource in the jQuery setup by
source:'<?=$this->Html->url(array("controller" => "countries","action"=> "find")); ?>',
And try to comment-out (just to make sure if the condition is not met by the request when autocomplete makes its call)
if ($this->request->is('ajax')) {
condition

Update stock price using ajax

I am doing a small personal web portfolio in order to learn web development. I have a list of all the stocks that I have "bought" and I would like to update the price in real-time from yahoo finance. I can already do the price update but I override the table that I display the stocks with a new one that is called using javascript.
I know there must be a cleaner way. I am trying to update the price using javascript but I don't think I am doing everything right.
Here is what I have so far.
Portfolio.php displays all the stocks I have
<?php foreach ($shares as $row): ?>
<tr >
<td><?php echo $row["symbol"];?></td>
<td><?php echo $row["name"];?></td>
<td style="text-align: right;"><?php echo $row["shares"];?></td>
<td id="price" style="text-align: right;">$ <?php echo number_format($row["price"],2);?></td>
<td style="text-align: right;"><?php
$change = number_format($row["change"],2);
echo sprintf( "%+1.2f", $change );
echo " ( ";
echo $row["pct"];
echo " )";
?></td>
<td style="text-align: right;">$ <?php echo $row["dayGain"];?></td>
<td style="text-align: right;">$ <?php echo number_format($row["total"],2);?></td>
</tr>
<?php endforeach; ?>
</table>
<script type="text/javascript" src="../html/js/update.js" ></script>
Then I have update.php which returns all the stock information from yahoo finance as a json
<?php
// configuration
require("../includes/config.php");
//query user's portfolio
$rows = query("SELECT * FROM shares WHERE id = ?", $_SESSION["id"]);
$cash = query("SELECT cash FROM users WHERE id = ?", $_SESSION["id"]);
//create array to store the shares
$shares = array();
//for each of the user info
foreach($rows as $row){
$yql_base_url = "http://query.yahooapis.com/v1/public/yql";
$yql_query = "select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22".$row['symbol']."%22)%0A%09%09";
$env = "env=http%3A%2F%2Fdatatables.org%2Falltables.env";
$yql_full_query = $yql_base_url . "?q=" . $yql_query . "&format=json&" . $env;
$session = curl_init($yql_full_query);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
$json = curl_exec($session);
$stock = json_decode($json);
if($stock->query->results !== false){
$shares [] = array(
"symbol" => $stock->query->results->quote->symbol,
"price" => $stock->query->results->quote->LastTradePriceOnly
);
}
}
$return = array("price" => $shares );
echo json_encode($return);
?>
And the third file is update.js in which I am trying to have javascript
$(document).ready(function(){
function stock() {
$(function() {
$.getJSON('../update.php',function(result){
$("div#price2").html(result.price);
});
});
stock();
setInterval(stock(), 10000);
});
});
If I go directly to update.php I can view the prices as json. I think the problem lies with the update.js file but I cannot figure out what the problem is. I cannot even print Hello from update.js in the price field.
What I am trying to do is display the stocks that I have stored in the database and then update the price using ajax and javascript. Any help would be appreciated. Thanks in advance.
Use php's json functions coupled with a .getJSON to update it... Here's some example code:
// pull_stock_price.php
<?php
$return = array("content" => "New Stock Price: $2000");
json_encode($return);
?>
// Jquery to pull stock price once every 10 seconds:
function stock() {
$(function() {$.getJSON("pull_stock_price.php",function(result){
$("#StockPrice").html(result.content);
});
});
stock();
setInterval(stock, 10000);
// HTML!
<td><div id="StockPrice"></div></td>
What this does: Every 10 seconds the user's browser will pull pull_stock_price.php and will take the content provided from the json and update . You can have pull_stock_price.php pull from the database, curl or really anywhere and format the data how you want it.

Categories