I am trying to hidden/show image file upload section if dropdown list is select option "2", if user select option "1" it should be display image upload option.
So for example is user select as category "Ponuda" it should display image file upload, if user select potraznja it should hidden image file upload.
createpostview.php
<h2><?= $title;?></h2>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
</script>
<?php echo form_open_multipart('posts/create/');?>
<?php echo validation_errors();?>
<div class="row">
<div class="col-md-4 col-md-offset-4">
<div class="form-group">
<label>Mjesto Polaska</label>
<input type="text" class="form-control" name="mjestoPolaska" placeholder="Mjesto Polaska">
</div>
<div class="form-group">
<label>Mjesto Odredista</label>
<input type="text" class="form-control" name="mjestoOdredista" placeholder="Mjesto Odredista">
</div>
<div class="form-group">
<label>Datum Polaska</label>
<input type="date" id="datepicker" min=<?php echo date('Y-m-d');?> class="form-control" name="datumPolaska" placeholder ="Datum Polaska" >
</div>
<div class="form-group">
<label>Datum Povratka</label>
<input type="date" id="datepicker1" min=<?php echo date('Y-m-d');?> class="form-control" name="datumPovratka" placeholder="Datum Povratka">
</div>
<div class="form-group">
<label>Cijena</label>
<input type="text" class="form-control" name="cijena" placeholder="Cijena">
</div>
<div class="form-group">
<label for="select">Broj slobodnih mjesta</label>
<select class="form-control" id="select" name="brojMjesta">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>
</div>
<div class="form-group">
<label for="kategorije">Kategorija</label>
<?php
echo '<select class="form-control" id="kategorije" name="category_id">';
foreach($categories as $category) :
echo '<option value="' . $category['id'] . '">' . $category["name"] . '</option>';
endforeach;
echo '</select>';
?>
</div>
<div class="form-group">
<label>Postavi sliku:</label>
<input type="file" name="userfile" size="20">
</div>
<div class="form-group">
<label>Opis:</label>
<textarea class="form-control" rows="5" id="comment" name="opis"></textarea>
</div>
<button type="submit" class="btn btn-primary btn-block">Submit</button>
</div>
</div>
JavaScript
<script>
var element = document.getElementById("category_id");
element.onchange = function(){
var hiddenDiv = document.getElementById("showMe");
hiddenDiv.style.display = (this.value=="")?"none":"block";}
</script>
You should try something like blew
get select value on change using javascript/jquery
<div class="form-group" id="img_upload">
<label>Postavi sliku:</label>
<input type="file" name="userfile" size="20">
</div>
$('#kategorije').on('change', function(){
var value = $(this).find(":selected").text();
if (value == 1) {
$("#img_upload").hide();
} else {
$("#img_upload").show();
}
});
Base from the html you provided, write a javascript like this:
$(function(){
$('#kategorije').on('change', function(){
var selected = $(this).val();
if (selected == 1) {
// hide the parent element of input
$('input[name=userfile]').parent().show();
} else {
// show the parent element of input
$('input[name=userfile]').parent().hide();
}
});
});
Related
The question I've got in my test goes like so.
You have 1 select with 2 options(item number1 and item number2) and 2 input fields(price,weight). How would you make the input fields change without writing in them?
So after a long time of searching and trying stuff out (without much luck) I've learned that I need to use ajax for this to work. so I have tried a bunch and this is the code I've tried edit so it would work.
getAllproduct is just a select that fetches all the data inside my table with products. this is id, name, item_number, price, weight. anyhow here is my code
<?php
$sth = $db->prepare("SELECT `price`,`weight` FROM product");
$sth->execute();
$row = $sth->fetch(PDO::FETCH_ASSOC);
$row = array();
json_encode($row);
?>
product.php
<div class="form-group col-2">
<label for="product">Item number</label>
<?=#$error['product']?>
<select class="form-control" name="product" id="product" onChange="getproduct(this.value)">
<?php foreach ($csv->getAllproduct() as $csv) { ?>
<option value="<?= #$csv->id ?>" selected><?= #$csv->product?></option>
<?php } ?>
</select>
</div>
<div class="form-group col-2">
<label for="weight">weight</label>
<?=#$error['weight']?>
<input type="text" name="weight" id="weight" class="form-control">
</div>
<div class="form-group col-2">
<label for="price">price</label>
<?=#$error['price']?>
<input type="text" name="price" id="price" class="form-control">
</div>
<div class="input-group">
<button type="submit" style="margin-left:15px; margin-bottom: 15px; z-index: 5" class="btn btn-success" value="Opret" name="btn_opret_maal">Submit</button>
</div>
<script>
function getproduct(val){
$.ajax({
type:"POST",
url:"pages\call.php",
data: 'product='+val,
success: function(response){
var result = JSON.parse(response);
if (result.response == true) {
var data = result.rows;
$("#weight").val(data[0].weight);
$("#price").val(data[0].price);
}else if (result.response == false) {
$('#product').append('<option>No products were found!</option>');
}
}
});
}
</script>
What I expect to be able to do is select an item number and it will automatically populate the inputfields price and weight with the data inside the database from the item number.
I haven't learned a lot of Ajax/js so Any help is appreciated.
Attempt: on other project using this code. havent gotten it to work yet.
<form class="row" method="POST" >
<div style="border-color:#dddddd;" class="dropdown-divider col-12"></div>
<script>$('#Varenummer').on('change', function() {
var selectedOption = $(this).find('option:selected');
$('#Tolminus').val(selectedOption[0].dataset.Tolminus);
$('#Tolplus').val(selectedOption[0].dataset.Tolplus);
});
</script>
<div class="form-group col-2">
<label for="Varenummer">Varenummer</label>
<?= #$error['Varenummer'] ?>
<select class="form-control" name="Varenummer" id="Varenummer">
<?php
foreach ($csv->getAllVarenummer() as $csv) {?>
<option value="<?= #$csv->id ?>" data-Tolminus="<?= #$csv->Tolminus ?>"
data-Tolplus="<?= #$csv->Tolplus ?>"><?= #$csv->Varenummer ?></option>
<?php }?>
</select>
</div>
<div class="form-group col-2">
<label for="Tolminus">Tol -</label>
<?= #$error['Tolminus'] ?>
<input type="text" name="Tolminus" id="Tolminus" class="form-control" value="">
</div>
<div class="form-group col-2">
<label for="Tolplus">Tol +</label>
<?= #$error['Tolplus'] ?>
<input type="text" name="Tolplus" id="Tolplus" class="form-control" value="">
</div>
<div class="input-group">
<button type="submit" style="margin-left:15px; margin-bottom: 15px; z-index: 5" class="btn btn-success" value="Opret" name="btn_opret_maal">Submit</button>
</div>
the jquery scrips and others are added in the footer.
As you asked above in comments: i need it to the input to change when i select an option. can i still only use php?...
Yes.
You might not need ajax at all. For your task I'd recommend to preload weight and price values into data- attributes of corresponding option elements. Then, on the select change, just get those values and paste them to inputs.
$('#product').on('change', function() {
var selectedOption = $(this).find('option:selected');
$('#weight').val(selectedOption[0].dataset.weight);
$('#price').val(selectedOption[0].dataset.price);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group col-2">
<label for="product">Item number</label>
<select class="form-control" name="product" id="product">
<option disabled selected>Choose product...</option>
<option value="1" data-weight="100" data-price="1000">Product 1</option>
<option value="2" data-weight="50" data-price="200">Product 2</option>
<option value="3" data-weight="25" data-price="115">Product 3</option>
</select>
</div>
<div class="form-group col-2">
<label for="weight">weight</label>
<input type="text" name="weight" id="weight" class="form-control">
</div>
<div class="form-group col-2">
<label for="price">price</label>
<input type="text" name="price" id="price" class="form-control">
</div>
<div class="input-group">
<button type="submit" style="margin-left:15px; margin-bottom: 15px; z-index: 5" class="btn btn-success" value="Opret" name="btn_opret_maal">Submit</button>
</div>
For the PHP generated select (assuming the getAllproduct method returns weight and price properties):
...
<div class="form-group col-2">
<label for="product">Item number</label>
<?=#$error['product']?>
<select class="form-control" name="product" id="product">
<?php foreach ($csv->getAllproduct() as $csv) { ?>
<option value="<?= #$csv->id ?>" data-weight="<?= #$csv->weight ?>" data-price="<?= #$csv->price ?>"><?= #$csv->product?></option>
<?php } ?>
</select>
</div>
...
I have created dynamic buttons in php. I need to get the value of that button when particular button is click. And when we click the button, all information is fetch in to the form.
Here is my code for buttonclick
<?php
function dash()
{
include 'config.php';
$sql = "SELECT roomno FROM roombook";
if($result = mysqli_query($db, $sql))
{
$str = '';
while($row = mysqli_fetch_array($result))
{
// generate array from comma delimited list
$rooms = explode(',', $row['roomno']);
//create the dynamic button and set the value
foreach ( $rooms as $k=>$v )
{
$str .= '<input type="button" onClick="showDiv()" name="btn_'.$k.'" value="'.$v.'" id="btn_'.$k.'"/>';
}
}
return $str;
}
else {
echo "ERROR: Could not able to execute $sql. " . mysqli_error($db);
}
mysqli_close($db);
}
?>
<!Doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>room boking</title>
<link href="css/bootstrap1.min.css" rel="stylesheet">
<link rel="stylesheet" href="css/front.css">
</head>
<body>
<form method="post" action="">
<div class =" row box col-md-4" >
<div style="color:black"><?php echo dash();?></div>
</div>
</form>
Here fetching the value in form code
<!DOCTYPE html>
<?php
include 'config.php';
if(isset($_POST['book']))
{
$roomno=$_POST['roomno'];
$roomtype=$_POST['roomtype'];
$location=$_POST['location'];
$charges=$_POST['charges'];
$firstname=$_POST['firstname'];
$lastname=$_POST['lastname'];
$address=$_POST['address'];
$city=$_POST['city'];
$state=$_POST['state'];
$pincode=$_POST['pincode'];
$mobilenumber=$_POST['mobilenumber'];
$idtype=$_POST['idtype'];
$idnumber=$_POST['idnumber'];
$Adate=$_POST['Adate'];
$Ldate=$_POST['Ldate'];
//echo $roomno."<br>".$roomtype."<br>".$location."<br>".$charges."<br>".$firstname."<br>".$lastname."<br>";
if(strlen($firstname)<3)
{
echo "<script>alert('First name is to short')</script>";
}
else if(strlen($lastname)<3)
{
echo "<script>alert('Last name is to short')</script>";
}
else if(strlen($address)<3)
{
echo "<script>alert('UserName name is to short')</script>";
}
else
{
$query=" INSERT INTO customerbook(roomno,roomtype,location,charges,firstname,lastname,address,city,state,pincode,mobilenumber,idtype,idnumber,Adate,Ldate) VALUES('$roomno','$roomtype','$location','$charges','$firstname','$lastname','$address','$city','$state','$pincode','$mobilenumber','$idtype','$idnumber','$Adate','$Ldate')";
//$query="INSERT INTO customerbook(roomno,roomtype,location,charges,firstname,lastname,address,state,city,pincode,mobilenumber,idtype,idnumber,Adate,Ldate) VALUES('$roomno','$roomtype','$location','$charges','$firstname','$lastname','$address','$state,','$city','$pincode','$mobilenumber','$idtype','$idnumber','$Adate','$Ldate')";
if(mysqli_query($db, $query))
{
echo "<script>alert('booking seccessfully')</script>";
//header("Location:login.php");
}
else echo "error";
}
}
$sql = "SELECT roomno,roomtype,location,charges FROM roombook where roomno='101'";
if($result = mysqli_query($db, $sql)){
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_array($result)){
$roomno=$row['roomno'];
$roomtype=$row['roomtype'];
$location=$row['location'];
$charges=$row['charges'];
}
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($db);
?>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>booking Form</title>
<!-- Bootstrap -->
<link href="css/bootstrap1.min.css" rel="stylesheet">
<link href="css/book.css" rel="stylesheet">
</style>
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="js/jquery-1.12.4.js"></script>
<script src="js/book1.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="head" id="link">
<div class="panel panel-primary" style="margin:20px;">
<div class="panel-heading">
<center><h3 class="panel-title">booking Form</h3></center>
</div>
<div class="panel-body">
<form method="post" action="">
<div class="col-md-12">
<div class="form-group col-md-12 ">
<label for="roomno">Room Number* </label>
<input type="text" class="form-control input-sm" name="roomno" value='<?php echo $roomno; ?>' placeholder="">
</div>
<div class="form-group col-md-6">
<label for="type">Room Type*</label>
<input type="text" class="form-control input-sm" name="roomtype" value='<?php echo $roomtype; ?>' placeholder="">
</div>
<div class="form-group col-md-6">
<label for="location">Location*</label>
<input type="text" class="form-control input-sm" name="location" placeholder="">
</div>
<div class="form-group col-md-12">
<label for="charges">charges*</label>
<input type="text" class="form-control input-sm" name="charges" placeholder="">
</div>
<div class="form-group col-md-6">
<label for="customer name">First Name*</label>
<input type="text" class="form-control input-sm" name="firstname" placeholder="">
</div>
<div class="form-group col-md-6">
<label for="customer name">Last Name*</label>
<input type="text" class="form-control input-sm" name="lastname" placeholder="">
</div>
<div class="form-group col-md-12">
<label for="address">Address*</label>
<textarea class="form-control input-sm" name="address" rows="3"></textarea>
</div>
<div class="form-group col-md-4">
<label for="city">City*</label>
<input type="text" class="form-control input-sm" name="city" placeholder="">
</div>
<div class="form-group col-md-4">
<label for="state">State*</label>
<input type="text" class="form-control input-sm" name="state" placeholder="">
</div>
<div class="form-group col-md-4">
<label for="pincode">Pincode</label>
<input type="text" class="form-control input-sm" name="pincode" placeholder="">
</div>
<div class="form-group col-md-12">
<label for="mobile">Mobile Number*</label>
<input type="text" class="form-control input-sm" name="mobilenumber" placeholder="">
</div>
<div class = "form-group col-md-12">
<label for="years">Id Type *</label>
<select class="form-control input-sm" name="idtype">
<option>-- Select Id Card --</option>
<option>Pancard</option>
<option>Adhar Card</option>
<option>voting card</option>
</select>
</div>
<div class="form-group col-md-12">
<label for="idnumber">Id Number</label>
<input type="text" class="form-control input-sm" name="idnumber" placeholder="">
</div>
<div class="form-group col-md-6">
<label for="arrival">Arrival Date</label>
<input type="text" class="form-control input-sm datepicker" name="Adate" placeholder="">
</div>
<div class="form-group col-md-6">
<label for="arrival">Leaving Date</label>
<input type="text" class="form-control input-sm datepicker" name="Ldate" placeholder="">
</div>
</div>
<div class="col-md-12">
<div class="form-group col-md-12 " >
<center><input type="submit" class="btn btn-primary" value="Submit" name="book"/><center>
</div>
</div>
</form>
</div>
</div>
</script>
</body>
</html>
You can create your button like this
$str .= '<input type="button" onClick="showDiv()" data-atribute-id="valueyouwant" name="btn_'.$k.'" value="'.$v.'" id="btn_'.$k.'"/>';
Script should be like
$("button").click(function() {
alert(this.id); OR
alert($(this).attr('id')); OR
alert($(this).attr('data')); OR
var btnid = $(this).attr('data');//which give you current clicked btn id
});
You can use this:
// is going to select all elements that its name start with *btn_* (your dynamic buttons)
$('[name^="btn_"]').click(function() {
//get the value of the button that was clicked
var buttonValue = $(this).val();
// send data to the other file using the action attribute of the form
$('form').submit();
});
Hope that can help.
I am trying to pass data through a text box which is selected through the 'other' in select option. However, when I run the program, the data is not passed. Any ideas how to resolve this? here is the code that I am using. I have added most of the code below. I have to pass information through the select option in the form of a text box. However the information is not passed. Is there any other method that can do this, passing through text to another page?
<?php include_once("header.php"); ?>
<?php
$q_sel = "select * from tbl_drug";
$r_sel = mysql_query($q_sel);
?>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$( document ).ready(function() {
$('#my_textarea').hide();
$('#Quantity').change(function()
{
var o = $(this).find('option:selected').val();
console.log(o);
if(o=='other') $('#my_textarea').show(); else $('#my_textarea').hide();
});
});
</script>
</head>
<body style="background-color: #25383c;background-image: url(img/background.png);">
<?php include_once("nav.php"); ?>
<h1> Medication Appropriateness Index</h1>
<div class="container-fluid">
<div class="row">
<div class="col-sm-12">
<div class="well">
<form class="form-horizontal" role="form" action="save_drug.php" method="post">
<div class="form-group">
<label class="control-label col-sm-2">Drug:</label>
<div class="col-xs-3">
<select name="drug" id="Drug" class="form-control" required="">
<option value="" selected="" disabled="">Please select A drug...</option>
<?php
while($r1 = mysql_fetch_array($r_sel))
{ ?>
<option value="<?php echo $r1['d_id']; ?>"><?php echo $r1['drug_name']; ?></option>
<?php
}
?>
</select>
</div>
</div>
<script>
$(function() {
$("#dose").tooltip();
});
</script>
<div class="form-group">
<label class="control-label col-sm-2">Route:</label>
<div class="col-xs-3">
<select id="Quantity" name="quantity" class="form-control" required="">
<option value="" selected="" disabled="">Please select A dosage...</option>
<option value="PO">PO</option>
<option value="IV">IV</option>
<option value="PR">PR</option>
<option value="Topically">Topically</option>
<option value="other">Other (please specify)</option>
</select>
<textarea name="my_textarea" id="my_textarea"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input type="hidden" name="patient_id" value="<?php echo $_GET['patient_id']; ?>">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
always use 'name' attribute for inputs , because only name can send data on submit.
<textarea name="my_textarea" id="my_textarea"></textarea>
I want to display form 1 if drop down value selected is one and similarly display form 2 if drop down value selected is two .
I am using JS to do this. Here is the code .please HELP ME.
I am not aware of JQuery so please help me from basics if the solution is in JQuery
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" type="text/css" href="asset_sim.css">
<script>
$('p select[name=asset_sim]').change(function () {
if ($(this).val() == 'asset') {
$('#asset_form').show();
} else {
$('#sim_form').show();
}
});
$('p select[name=asset_sim]').change(function () {
if ($(this).val() == 'sim') {
$('#sim_form').show();
} else {
$('#asset_form').hide();
}
});
</script>
</head>
<body>
<?php
include 'header.php';
include 'footer.php';
include 'config.php';
//
//if (isset($_POST['sub'])) {
// $username = filter_input(INPUT_POST, 'User_name');
// $fullname = filter_input(INPUT_POST, 'Full_name');
// $email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
// $roll = filter_input(INPUT_POST, 'role');
// $contact = filter_input(INPUT_POST, 'contact_no');
//
//
// if (($sql = $conn->prepare("insert into tmtool.user_master (Username,Full_name,Email,Role,Contact_no)"
// . "values (?,?,?,?,?)")) == FALSE) {
// echo "false";
// }
// $sql->bind_param('sssss', $username, $fullname, $email, $roll, $contact);
//
// // 2nd query for execution
//
// if (($sql1 = $conn->prepare("insert into tmtool.login (Username,Password) values (?,?)")) == FALSE) {
// echo "false";
// }
// $sql1->bind_param('ss', $username, $tmppass);
//
//inserting userdetails into database
}
?>
<div id="page-wrapper">
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Assets and SIM Management</h1>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-heading">
<label>Enter Asset Details</label>
</div>
<div class="panel-body">
<p>Asset or Sim details :
<select name="asset_sim" required="required">
<option value="">-- Select an Option --</option>
<option value="asset">Enter Asset Details</option>
<option value="sim">Enter SIM Details</option>
</select>
</p>
<div class="dataTable_wrapper">
<div id="asset_form">
<form action="AssetMaster.php" method="POST" role="form">
<div class="col-lg-6">
<div class="form-group">
<label>Device Name</label>
<select name="device_name">
<option>Laptop</option>
<option>Mobile</option>
<option>Data Card</option>
</select>
</div>
<div class="form-group">
<label>Company name</label>
<input class="form-control" name="company_name" type="text" id="company_name" required="required" placeholder="Enetr Company name" title="Please Enetr company name of Device">
</div>
<div class="form-group">
<label>Model Number</label>
<input class="form-control" name="Model_number" type="text" id="model_number" required="required" placeholder="Enetr Model number" title="Enter model number of Your Device ">
</div>
<div class="form-group">
<label>OS version</label>
<input class="form-control" name="OS_version" required="required" id="Os-versionid" placeholder="Enter OS version detail" oninvalid="setCustomValidity('Enter OS version details')" onchange="try {
setCustomValidity('')
} catch (e) {
}"/>
</div>
</div>
<div class="col-lg-12">
<button type="submit" class="btn btn-primary" id="submit" name="sub" data-toggle="modal" data-target="#myModal">Submit</button>
<button type="reset" class="btn btn-primary">Reset</button>
</div>
</form>
</div>
</div>
<div class="dataTable_wrapper">
<div id="sim_form">
<form action="AssetMaster.php" method="POST" role="form">
<div class="col-lg-6">
<div class="form-group">
<label>Type</label>
<select name="sim_type">
<option>Prepaid</option>
<option>Postpaid</option>
</select>
</div>
<div class="form-group">
<label>Simcard Number</label>
<input class="form-control" name="simcard_no" type="text" id="simcard_name" required="required" placeholder="Enetr Simcard Number" title="Please Enter Simcard Number">
</div>
<div class="form-group">
<label>Service Provider</label>
<input class="form-control" name="service_provider" type="text" id="service_provider" required="required" placeholder="Enter Service provider name" title="Enter Service provider name ">
</div>
</div>
<div class="col-lg-12">
<button type="submit" class="btn btn-primary" id="submit" name="sub" data-toggle="modal" data-target="#myModal">Submit</button>
<button type="reset" class="btn btn-primary">Reset</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- jQuery -->
<!--<script src="../bower_components/jquery/dist/jquery.min.js"></script>-->
<!-- Bootstrap Core JavaScript -->
<!--<script src="../bower_components/bootstrap/dist/js/bootstrap.min.js"></script>-->
<!-- Metis Menu Plugin JavaScript -->
<script src="../../bower_components/metisMenu/dist/metisMenu.min.js"></script>
<!-- DataTables JavaScript -->
<script src="../../bower_components/DataTables/media/js/jquery.dataTables.min.js"></script>
<script src="../../bower_components/datatables-plugins/integration/bootstrap/3/dataTables.bootstrap.min.js"></script>
<!-- Custom Theme JavaScript -->
<script src="../../dist/js/sb-admin-2.js"></script>
<!-- Page-Level Demo Scripts - Tables - Use for reference -->
<script>
$(document).ready(function () {
$('#dataTables-example').DataTable({
responsive: true
});
});
</script>
</body>
</html>
Here you can see a working snippet:
$(document).ready(function(){
var selector = $("#form_selector");
var last = null;
function update(){
var selected = selector.val();
if (last)
$("#form_" + last).css('display', 'none');
$("#form_" + selected).css('display', 'block');
last = selected;
}
update();
selector.on("change", update);
});
form {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="form_selector">
<option value="1">1</option>
<option value="2">2</option>
</select>
<hr>
<form name="form" id="form_1">
<input type="text" name="username" placeholder="Your Username"></input><br>
<input type="submit" value="Submit Form 1"></input><br>
</form>
<form name="form" id="form_2">
<input type="email" name="email" placeholder="Your Email"></input><br>
<input type="submit" value="Submit Form 2"></input><br>
</form>
I have a form that collects user data and when the user clicks save it uses ajax to pass the data to a php script that executes an insert statement into a database. When I debug through the scripts and look at the variables coming in from the ajax request the structure of the php array has the wrong structure for the last 4 variables in which the value is added on to the variable name instead of like the first 3 variables.
Does any one have any advice as to why this is happening? and how I can fix it?
units.php
<div class="modal fade" id="AddModal" tabindex="-1" role="dialog" aria-labelledby="AddModal" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="modal-title" id="AddModal">Add Unit Code </h3>
</div> <!--modal-header-->
<div class="modal-body">
<form id="add-form" class="form-horizontal">
<fieldset>
<!-- Form Name -->
<!--<legend>Form Name</legend>-->
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="addUnitId">Unit Id</label>
<div class="col-md-2">
<input name="addUnitId" class="form-control input-sm" id="addUnitId" required="" type="text" maxlength="6" placeholder="">
</div>
</div>
<!-- Select Basic -->
<div class="form-group">
<label class="col-md-4 control-label" for="addDivId" >Div Id</label>
<div class="col-md-2">
<select name="addDivId" class="form-control" id="addDivId">
<option value=""></option>
<?php
// Populate the drop down select box from the database
$query1=mysql_query("select * from divisions where div_id <> '' ");
while($row=mysql_fetch_assoc($query1)){
$str = $row['div_id']
?>
<option value="<?php echo str_pad($str,4,'37', STR_PAD_LEFT); ?>">
<?php
echo str_pad($str,4,'37', STR_PAD_LEFT);
echo "  " ;
echo $row['long_desc'] ?>
</option>
<?php
} // close while loop
?>
</select>
</div>
</div>
<!-- Select Basic -->
<div class="form-group">
<label class="col-md-4 control-label" for="addTitleOrg">Title Org</label>
<div class="col-md-4">
<select name="addTitleOrg" class="form-control" id="addTitleOrg">
<option value=""></option>
<?php
// Populate the drop down select box from the database
$query2=mysql_query("select l1l5, ltitl, stitl from tl2l5 where status='A' ");
while($row=mysql_fetch_assoc($query2)){
?>
<option value="<?php echo $row['l1l5']; ?>">
<?php
echo $row['l1l5'];
echo "  " ;
echo $row['ltitl'] ?>
</option>
<?php
} // close while loop
?>
</select>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="addShortDesc">Short Desc</label>
<div class="col-md-2">
<input name="addShortDesc" class="form-control input-sm" id="addShortDesc" disabled="disabled" type="text" placeholder="">
</div>
</div>
<!-- Text input -->
<div class="form-group">
<label class="col-md-4 control-label" for="addLongDesc">Long Desc</label>
<div class="col-md-4">
<input name="addLongDesc" class="form-control input-sm" id="addLongDesc" disabled="disabled" type="text" placeholder="" >
</div>
</div>
<!-- Text input -->
<div class="form-group">
<label class="col-md-4 control-label" for="addUnitDesc">Comments</label>
<div class="col-md-4">
<input name="addUnitDesc" class="form-control input-sm" id="addUnitDesc" maxlength="50">
</div>
</div>
<!-- Select Basic -->
<div class="form-group">
<label class="col-md-4 control-label" for="addEnabled">Enabled</label>
<div class="col-md-2">
<select name="addEnabled" class="form-control" id="addEnabled">
<option value="Y">Y</option>
<option value="N">N</option>
</select>
</div>
</div>
</fieldset>
</form>
</div> <!--modal-body-->
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="button" id="saveAdd" name="saveAdd" class="btn btn-primary">Add</button>
</div> <!--modal-footer-->
</div> <!--modal-content-->
</div> <!--modal-dialog-->
</div> <!--modal-fade -->
JavaScript file
$('#saveAdd').on('click', function() {
var data ={
unit_id : $('#addUnitId').val(),
div_id : $('#addDivId').val(),
title_org : $('#addTitleOrg').val(),
short_desc : $('#addShortDesc').val(),
long_desc : $('#addLongDesc').val(),
unit_desc : $('#addUnitDesc').val(),
avail_ind : $('#addEnabled').val()
};
alert(data);
// alert(unit_id + " " + div_id + " " + title_org + " " + short_desc + " " + long_desc + " " + unit_desc + " " + avail_ind);
$.ajax({
type: "POST",
url: "test.php?cmd=add",
data: data
});
});
PHP file
require_once ('config/config.php');
$conn = new PDO('mysql:host=' . DBHOST . '; dbname=' . DBNAME ,DBUSER,DBPASS);
$unit_id = $_REQUEST['unit_id'];
$div_id = $_REQUEST['div_id'];
$title_org = $_REQUEST['title_org'];
$short_desc = $_REQUEST['short_desc'];
$long_desc = $_REQUEST['long_desc'];
$unit_desc = $_REQUEST['unit_desc'];
$avail_ind = $_REQUEST['avail_ind'];
// PREPARE INSERT STATEMENT
$stmt = $conn->prepare("INSERT INTO units
(unit_id, div_id, title_org, short_desc, long_desc, unit_desc, avail_ind)
VALUES ($unit_id','$div_id','$title_org','$short_desc','$long_desc','$unit_desc','$avail_ind')
WHERE NOT EXISTS (SELECT * FROM units WHERE unit_id = '$unit_id')");
UPDATE:
#Sam when I changed the $_REQUEST to $_POST the array was empty, array(0)
When I use the $_GET and debug through the scripts it still gives me the improper structure of the PHP array
Try this:
var vdata=[];
$.each(data,function(k,v){
var str=k+'='+v;
vdata.push(str);});
}
vdata=vdata.join("&");
and in your ajax-post:
data: vdata;