Dropdown Onchange and Passing JavaScript Value to PHP - javascript

Hello I have a problem on how should I send a JavaScript value to PHP.
Here is my form:
Dropdown Question from database:
fiddle code
<form action="action/survey">
<div class="form-group">
<label class="control-label col-sm-2" for="email">Select Question</label>
<div class="col-sm-10">
<select class="form-control" id="mySelect" onchange="option()">
<?php
$sql = mysqli_query($con,"SELECT *,(SELECT GROUP_CONCAT(answer) AS `option`FROM `survey_anweroptions` WHERE survey_qID = sq.survey_qID) `option` FROM `survey_questionnaire`sq WHERE sq.survey_ID = $id");
while ($q = mysqli_fetch_array($sql)) {
?>
<option value="<?php echo $q[0]?>"><?php echo $q[2]?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label " for=""></label>
</div>
<?php
$sql = mysqli_query($con,"SELECT *,(SELECT GROUP_CONCAT(answer) AS `option`FROM `survey_anweroptions` WHERE survey_qID = sq.survey_qID) `option` FROM `survey_questionnaire`sq WHERE sq.survey_ID = 1 AND survey_qID = 1");
$d1= mysqli_fetch_array($sql);
?>
<div class="form-group">
<label class="control-label col-sm-2" for="">Question</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="" placeholder="" value="<?php echo $d1[2]?>">
</div>
</div>
<?php
$variable = $d1[3];
$z = 1;
$piece = explode(",", $variable);
foreach ($piece as $key => $value) {
?>
<div class="form-group">
<label class="control-label col-sm-2" for="">Option <?php echo $z?> </label>
<div class="col-sm-10">
<input type="text" class="form-control" id="" placeholder="" value="<?php echo $value?>">
</div>
</div>
<?php
$z++;
}
?>
<div class="text-center">
<button type="submit" class="btn btn-default" name="">Update</button>
</div>
</form>
JavaScript:
function option(){
var x = document.getElementById("mySelect").value;
document.getElementById("demo").innerHTML = "You selected: " + x;
}
What I want is if I select 1 value on the drop-down, the value of option must be sent to a PHP variable in this query:
SELECT *, (
SELECT GROUP_CONCAT(answer) AS `option`
FROM `survey_anweroptions`
WHERE survey_qID = sq.survey_qID
) `option`
FROM `survey_questionnaire`sq
WHERE sq.survey_ID = 1
AND survey_qID = (**the value of option will go here**)

You should use name instead of id. and do print_r($_POST) to check weather post data coming or not. also you dont need javascript for this until you are using ajax to call your php script

like #Coder said you the inputs send to the server with it's name attribute not id attribute
you should change the select element to
<select class="form-control" id="mySelect" name="my_select" onchange="option()">
and retrieve it's value with
$_POST['my_select'] // if you use POST method on form submition
$_GET['my_select'] // if you use GET method on form submition
$_REQUEST['my_select'] // if you accept any method

Related

Select show hide div after specific values input

I'm basically trying to
Show upload div when status input valued="Tidak aktif"
Hide upload div when status input valued ="Aktif"
This is my code
<h2>EDIT STATUS PEGAWAI</h2>
<?php
$ambildata = $koneksi -> query ("SELECT * FROM diniyah WHERE ID ='$_GET[id]'");
$pecahdata = $ambildata -> fetch_assoc();
echo "<pre>" ;
print_r($pecahdata);
echo "</pre>";
?>
<h2>GANTI STATUS PEGAWAI : </h2>
<form method="post" enctype="multipart/form-data">
<select class="form-control form-control-lg" name="STATUS" id="STATUS">
<option value="Aktif">AKTIF</option>
<option value="Tidak Aktif">TIDAK AKTIF</option>
<div class="form-group" style="display:none;">
<input type="file" name="uploaddiniyah" class="form-control">
<button class="btn btn-primary" name="ubah">Konfirmasi</button>
</div>
</form>
<?php
if (isset($_POST['Tidak Aktif'])){
include'upload.php';
}else{
include'home.php';
}
?>
<?php
if (isset($_POST['ubah'])) {
$uploaddiniyah = true;
$namafoto = $_FILES ['uploaddiniyah']['name'];
$lokasifoto = $_FILES ['uploaddiniyah']['tmp_name'];
move_uploaded_file($lokasifoto, "../fotodokumen/".$namafoto);
//jk foto dirubah
$koneksi->query("UPDATE diniyah SET status='$_POST[STATUS]' WHERE ID='$_GET[id]'");
$update_gambar=mysqli_query($koneksi,"UPDATE diniyah SET uploaddiniyah='$namafoto' WHERE ID='$_GET[id]'");
echo "<div class='alert alert-info'> Data Tersimpan</div>";
}
?>
Is there a mistake on my code?
You can use basic js for do that like:
let status = document.getElementById('STATUS');
let upload = document.getElementById('upload');
status.onchange = function()
{
if(this.value === "Tidak Aktif"){
upload.style.display = 'block';
}else{
upload.style.display = 'none';
}
}
<select class="form-control form-control-lg" name="STATUS" id="STATUS">
<option value="Aktif">AKTIF</option>
<option value="Tidak Aktif">TIDAK AKTIF</option>
</select>
<div class="form-group" id='upload' style="display:none;">
<input type="file" name="uploaddiniyah" class="form-control">
</div>

Retain ajax populated value in dropdown

I have a form where two dropdowns are kept. When the value on first is selected, ajax call is made to show related results as second dropdown list. My issue is when value is selected on second dropdown and form is submitted the second dropdown list(which is being populated on basis of first selection made in first select box) gets empty. I want to retain the value into the second dropdown selected after form submit. Can I have some insight over the same.
<div class="form-group">
<div class="col-md-12">
<div class="col-md-3">
<label for="username" class="control-label">Select Level:</label>
</div>
<div class="col-md-9">
<select name="levels" class="form-control" required="" id = "level">
<?php $fnc->selectBoxsearchLevel("tbl_levels_master","id","level_title", $level_id) ; ?>
</select>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#level").change(function() {
var level_id = $(this).val();
if(level_id != "") {
$.ajax({
url:"get_units.php",
data:{l_id:level_id},
type:'POST',
success:function(response) {
//console.log (response);
var resp = $.trim(response);
$("#unit").html(resp);
}
});
} else {
$("#unit").html("<option value=''>------- Selected --------</option>");
}
});
});
</script>
<div class="form-group">
<div class="col-md-12">
<div class="col-md-3">
<label for="username" class="control-label">Select Unit:</label>
</div>
<div class="col-md-9">
<select name="units" class="form-control" required="" id= "unit">
<option>------- Select --------</option>
</select>
</div>
</div>
</div>
And my get_units.php
<?php
$db = new Database(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);
$level_id = $_POST['l_id'];
$sql = "select * from tbl where level=$level_id";
$res = $db->query($sql);
echo "<option value=''>------- Select --------</option>";
while($row = mysql_fetch_array($res)) {
echo "<option value='".$row['id']."'>".$row['title']."</option>";
}
?>

Jquery autocomplete combo box/selectbox using codeigniter

I want to ask, has someone ever created autocomplete using combo box / select box with code igniter?
I've tried but only managed to use autocomplete for 2 input text but I have another idea to create autocomplete with text combined with combo box. I've do created that but I have trouble my autocomplete in the text is successful but in the combo box does not work only show empty option. can someone help me? this is my source code
My Table : i probably using 2 table for autocomplete : 1. tb_produk and 2. tb_kategori_produk
https://imgur.com/a/xpysI | 2. https://imgur.com/a/DVgUl
My Controller : user.php
public function request_produk(){ //used for calling view
$data["kateprod"] = $this->db->where("f_status_kategori_produk","1")
->get("tb_kategori_produk")->result_array();
$this->theme->panel('user/v_request',$data);
}
public function mesin() //user for jquery called data
{
$keyword = $this->uri->segment(3);
$data = $this->db->from('tb_produk')->join('tb_kategori_produk','tb_kategori_produk.f_id_kategori_produk=tb_produk.f_kategori_produk')->like('f_nama_produk',$keyword)->get();
foreach($data->result() as $row)
{
$arr['query'] = $keyword;
$arr['suggestions'][] = array(
'value' =>$row->f_nama_produk,
'idpro' =>$row->f_id_produk,
'idkate' =>$row->f_id_kategori_produk,
'kategori'=>$row->f_nama_kategori_produk
);
}
echo json_encode($arr);
}
My Controller : v_request.php
<div id="content">
<script type="text/javascript">
var site = "<?php echo site_url();?>";
$(function() {
$(".autocomplete").autocomplete({
serviceUrl: site+"/user/mesin",
onSelect: function (suggestion) {
$("#v_idproduk").val(""+suggestion.idpro);
$("#v_kategori").val(""+suggestion.kategori);
$("#v_idkategori").val(""+suggestion.idkate);
}
});
});
</script>
<?php $id = $this->session->userdata('f_id_user');
<input type="hidden" name="dt[f_id_user]" value="<?php echo $this->session->userdata('f_id_user'); ?>">
<input type="hidden" id="v_idproduk" name="dt[f_id_produk]">
<input type="hidden" id="v_idkategori" name="dt[f_kategori_produk]">
<div class="form-group br-form"> <!-- This form group i used to autocomplete text -->
<div class="col-md-2">
<label class="control-label">Nama Mesin</label>
</div>
<div class="col-md-10">
<input type="search" class="autocomplete form-control" id="autocomplete1" name="nama_mesin" required/>
</div>
</div><br><br>
<div class="form-group br-form"> <!-- This form group i used to autocomplete combo box-->
<div class="col-md-2">
<label class="control-label">Kategori Mesin</label>
</div>
<div class="col-md-10">
<select id="v_kategori" name="dt[f_kategori_produk]" class="form-control" required>
<option value="">---Harap Pilih---</option>
<?php foreach ($kateprod as $key) { ?>
<option value="<?=$key['f_id_kategori_produk']?>" id="v_kategori"><?php echo $key["f_nama_kategori_produk"];?></option>
<?php } ?>
</select>
</div>
</div><br>
This is my demo
https://streamable.com/wvn25

Issue posting form via AJAX

I have the following form which I then send upon submit via AJAX to insert to a MySQL DB through Ajax. All inputbox in form have their own Id and I get them all in my .php process file except the ones "cas" and "dat" that do not seem to go through the AJAX posting process.
The form:
<form id="form">
<div class="form-group">
<label class="lab" for="nm">id</label>
<input disabled type="text" id="id" name="id" class="form-control" placeholder="Id">
</div>
<div class="form-group">
<input type="text" class="form-control" name="cas" id="cas" value="2">
<input type="text" class="form-control" name="dat" id="dat" value="2017-11-30">
</div>
<div class="form-group">
<label class="lab" for="nm">Product</label> <?php
//// function populate ($sql, $class,$name, $id, $title, $value,$option)
echo populate ("SELECT * FROM product_family order by product_type_id ASC","form-control","nm","nm","Select Product", "product_family", "product_family");?>
</div>
<div class="form-group">
<label class="lab" for="em">Win</label>
<input type="text" id="em" name="em" class="form-control allow_decimal" placeholder="Win">
</div>
<div class="form-group">
<label class="lab" for="hp">Drop</label>
<input type="text" id="hp" name="hp" class="form-control allow_decimal" placeholder="Drop">
</div>
<div class="form-group">
<label class="lab" for="ad">Currency</label> <?php
//// function populate ($sql, $class,$name, $id, $title, $value,$option)
echo populate ("SELECT * FROM currency order by id ASC","form-control","ad","ad","Select Currency", "currency", "currency");?>
</div>
<button type="button" id="save" class="btn btn-success" onclick="saveData()">Save</button>
<button type="button" id="update" class="btn btn-warning" onclick="updateData()">Update</button>
</form>
I then have the following JavaScript code triggering the Insert upon "save data" click in order to post the different inputbox values to my .php processing file:
function saveData(){
var id = $('#id').val();
var name = $('#nm').val();
var email = $('#em').val();
var phone = $('#hp').val();
var address = $('#ad').val();
var casino = $("#cas").val()
var date = $("#dat").val();
$.post('server.php?p=add', {id:id, nm:name, em:email, hp:phone, ad:address, cas:casino, dat:date}, function(data){
viewData()
$('#id').val(' ')
$('#nm').val(' ')
$('#em').val(' ')
$('#hp').val(' ')
$('#ad').val(' ')
})
}
function viewData(){
$.get('server.php', function(data){
$('tbody').html(data)
})
}
Then I try to read my "$_post" values on the PHP side:
if($page=='add'){
try{
$id = $_POST['id'];
$nm = $_POST['nm'];
$em = $_POST['em'];
$hp = $_POST['hp'];
$ad = $_POST['ad'];
$casino_id = $_POST['cas'];
$date = $_POST['dat'];
}
I perfectly get all variables except the dat and cas posts that do no appear in the $_post list. Listing all $_Post the following way:
$myfile = fopen("LOGPOST.txt", "w") or die("Unable to open file!");
foreach ($_POST as $key => $value){
$txt= $txt."{$key} = {$value}//";
gives the following output: id = //nm = F&B Sales//em = 1000//hp = 500//ad = EUR//
What am I doing wrong?

How to Update/Edit data in database with AngularJS

Working on a web app , I just added the below update code and it's not working .
The summary of all the below code is :
Click a Button called update
It brings out the FORM which should contain the values of the clicked/current product.
Now when I hit save in this form it should update the database but it is not.
I am using $_GET in PHP file (update.php) to get the current Product ID.And then getting all data of that product via that ID.
PS: There is no error in console.
UPDATE CODE:
<?php
include "includes/connection.php";
switch($_GET['action']) {
case 'update_entry' :
$data = json_decode(file_get_contents("php://input"));
$index = $data->id;
$productname = $data->pname;
$company = $data->company;
$price = $data->price;
$quantity = $data->quantity;
if(isset($productname) && !empty($productname) && isset($company) && !empty($company) && isset($price) && !empty($price) && isset($quantity) && !empty($quantity)){
$query = "UPDATE `product` SET `id`='$index',`name`='$productname',`company`='$company',`price`='$price',`quantity`='$quantity' WHERE id= $index";
if(mysqli_query($con, $query)) {
return true;
} else {
echo "Error: " . $sql . "<br />" . mysqli_error($con);
}
break;
}
}
?>
Controller :
myApp.controller("updateCtrl",['$scope','$http','$routeParams','$location',function($scope,$http,$routeParams,$location){
$scope.update = function(){
var currentId = $routeParams.id;
$http.post("update.php?action=update_entry",{'id':currentId})
.then(function(data){
$location.path('/viewproduct');
});
}
}]);
HTML:
<form style="padding:10px" ng-controller="updateCtrl">
<div class="form-group">
<label for="ProductName">Product Name</label>
<input type="text" class="form-control" placeholder="{{product.name}}" ng-model="productname" required>
</div>
<div class="form-group">
<label for="company">Company </label>
<input type="text" class="form-control" placeholder="{{product.company}}" ng-model="company" required>
</div>
<div class="form-group">
<label for="company">Price </label>
<input type="text" class="form-control" placeholder="{{product.price}}" ng-model="price" required>
</div>
<div class="form-group">
<label for="company">Quantity </label>
<input type="text" class="form-control" placeholder="{{product.quantity}}" ng-model="quantity" required>
</div>
<button type="submit" class="btn btn-default" ng-click="update()">Save updated data</button>
Cancel
<h1 ng-if="successMessage == 0">Great Data is Updated!</h1>
</form>
Update Button:
<td ng-controller="updateCtrl"><a class="btn btn-primary" href="#/updateproduct/action={{product.id}}" >Update</a></td>
Do like below
your view part
<form style="padding:10px" ng-controller="updateCtrl">
<div class="form-group">
<label for="ProductName">Product Name</label>
<input type="text" class="form-control" placeholder="{{product.name}}" ng-model="productname" required>
</div>
<div class="form-group">
<label for="company">Company </label>
<input type="text" class="form-control" placeholder="{{product.company}}" ng-model="company" required>
</div>
<div class="form-group">
<label for="company">Price </label>
<input type="text" class="form-control" placeholder="{{product.price}}" ng-model="price" required>
</div>
<div class="form-group">
<label for="company">Quantity </label>
<input type="text" class="form-control" placeholder="{{product.quantity}}" ng-model="quantity" required>
</div>
<button type="submit" class="btn btn-default" ng-click="update()">Save updated data</button>
Cancel
<h1 ng-if="successMessage == 0">Great Data is Updated!</h1>
</form>
<td><a class="btn btn-primary" ng-click="addProductData();" >Update</a></td>
Inside your controller do like below
$scope.addProductData=function(){
var updatedata=$.param({'action':'update','productname':$scope.productname,'company':$scope.company,'price':$scope.price,'quantity':$scope.quantity,'id':currentId});
$http({
method:'POST',
url:'update.php',
data:updatedata,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(function successCallback(response){
alert(response.data['msg']);
},function errorCallback(response) {
alert(response.data['msg']);
});
}
your update.php file should like below.
<?php
include "includes/connection.php";
$result=array();
if(isset($_REQUEST["action"]) && $_REQUEST["action"] !=""){
if($_REQUEST["action"]=="update"){
$productname = $_POST['productname'];
$company = $_POST['company'];
$price = $_POST['price'];
$quantity = $_POST['quantity'];
$id=$_POST['id'];
$query = "UPDATE `product` SET `name`='$productname',`company`='$company',`price`='$price',`quantity`='$quantity' WHERE id= $id";
if(mysqli_query($con, $query)) {
$result['msg']="updated successfully";
}else{
header("HTTP/1.0 401 Unauthorized");
$result['msg']="unable to updated";
}
echo json_encode($result);
}
}
?>
i think you may basic idea.now you can implement in your way.
Try to use ng-model="{{product.name}}}" and not the placeholder in HTML.
And in your controller pass that model:
$http.post("update.php?action=update_entry",$scope.product)
Then you should get some data in your PHP.
Have you checked your php alone to make sure that you can fetch and update data using the php without angular? I would use post as it is more friendly for retrieving and updating data.
I would also b separate your call to the php endpoint into a service (factory). I would also just pass the entire object back through to ensure that you aren't missing something unless you have a concern about bandwidth.
I would unit test php first. Then separate logic in angular. Then b step through in debug to see what's being passed from the view.
I think you should check this: https://github.com/eliarms/CustomerManagerApp
This is a simple customer management app using Angularjs and PHP. The goal of the application is to highlight a lot of the different features offered by AngularJS and demonstrate how they can be used together.

Categories

Resources