How to get dynamic buttons value when button is click in PHP? - javascript

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.

Related

How to check if content of an html element is empty?

I was building a simple PHP login form that contains both required fields and validation. regardless required fields, I want to display an error message for each input element that had not been filled. But I come across a problem on the way. The span element I use for styling does not disappear when there is no content in the span element. I wrote some javascript code and it did not work. I want the span element to hide when there is no content because the $nameerr equals to "" at the start. When the $nameerr equals to "Name Required" string, the span element should be visible only at the time. How to achieve that?
Note: I only want to test for $name and $nameerr first before implementing other variables, So other variable is "".
Here is my code for php:
<?php include('validate.php'); ?>
<!DOCTYPE html>
<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.0">
<title>Learning PHP</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="row justify-content-center" style="height:auto;background-color:#ffcb05;">
<div class="col-lg-4" style="background-color:#fcd670;">
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="post">
<div class="d-flex flex-column">
<div class="mb-3">
<label for="name" class="form-label">Name:</label>
<input type="text" name="name" id="name" class="form-control" placeholder="Please enter your name" style="width:100%;">
<span class="badge bg-danger float-end" id="error1">
<?php echo $nameerr; ?>
</span>
</div>
<div class="mb-3">
<label for="email" class="form-label">E-mail</label>
<input type="email" name="email" id="email" class="form-control" placeholder="Please enter your e-mail" style="width:100%;">
</div>
<div class="mb-3">
<label for="website" class="form-label">Website</label>
<input type="url" name="website" id="website" class="form-control" placeholder="Please enter your website" style="width:100%;">
</div>
<div class="mb-3">
<label for="comment">Comment</label>
<textarea name="comment" id="comment" cols="45" rows="5" class="form-control"></textarea>
</div>
<div class="mb-3">
<label>Gender</label>
<label for="male">Male</label>
<input type="radio" name="gender" id="male" value="male">
<label for="female">Female</label>
<input type="radio" name="gender" id="female" value="female">
<label for="other">Other</label>
<input type="radio" name="gender" id="other" value="other">
</div>
<div class="mb-3">
<button class="btn btn-primary float-end" type="submit">Submit</button>
</div>
</div>
</form>
</div>
</div>
</div>
<script>
var content=document.getElementById('error1').innerHTML;
if(content==""){
document.getElementById('error1').style.display="none";
}else{
ocument.getElementById('error1').style.display="block";
}
</script>
</body>
</html>
Here is my validate.php file:
<?php
$name=$email=$website=$comment=$gender='';
$nameerr=$emailerr=$websiteerr=$commenterr=$gendererr='';
if($_SERVER["REQUEST_METHOD"]=="POST"){
if(empty($_POST['name'])){
$nameerr="Name Required";
}else{
$name=validateInput($_POST["name"]);
$email=validateInput($_POST["email"]);
$website=validateInput($_POST["website"]);
$comment=validateInput($_POST["comment"]);
$gender=validateInput($_POST["gender"]);
echo $name."<br>".$email."<br>".$website."<br>".$comment."<br>".$gender."<br>";
}
}
function validateInput($data){
$data=trim($data);
$data=stripslashes($data);
$data=htmlspecialchars($data);
return $data;
}
In my opinion. I think you don't need to use javascript to show/hide error content.
You can try below block code:
<?php if(!empty($nameerr)): ?>
<span class="badge bg-danger float-end" id="error1">
<?php echo $nameerr; ?>
</span>
<?php endif; ?>
You have padding there.
so you can try removing the class badge
<span class="bg-danger float-end" id="error1">
<?php echo $nameerr; ?>
</span>
or remove the padding from that class
.badge {
display: inline-block;
/* padding: 0.35em 0.65em;*/
You may use a client side approach (javascript).
Detect on submit whether the name field is empty
If yes, make the error1 message visible, else make it not visible
Add more blocks for further validation, if you wish
If no further errors, return true (to submit)
So change
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="post">
to
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="post" onsubmit="return validateform();">
and change
<span class="badge bg-danger float-end" id="error1">
<?php echo $nameerr; ?>
</span>
to
<span class="badge bg-danger float-end" id="error1" style="display:none;">
Name Required !!!!
</span>
and add the following :
<script>
function myTrim(x) {
return x.replace(/^\s+|\s+$/gm,'');
}
function validateform() {
if(myTrim(document.getElementById('name').value)==""){
document.getElementById('error1').style.display="block";
return false;
}else{
document.getElementById('error1').style.display="none";
}
// if no errors at all
return true;
}
</script>

Show/Hidden content using Dropdown list

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();
}
});
});

Data entered in the form is not being sent to the Oracle Database

I am trying to create a registration form in Bootstrap and then connecting it to the Oracle Database but the data entered by the user isn't sending any value to the database. Please suggest what editing I should do.
<!DOCTYPE html>
<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">
<title>Home - Student Registration Form</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/datepicker.css" rel="stylesheet">
<style>
.error{
color: red;
}
</style>
</head>
<body>
<div class="container">
<div class="row">
<form id="regform" class="form-horizontal" action="NewFile.jsp">
<fieldset>
<!-- Form Name -->
<legend>Student Registration</legend>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="firstname">First Name</label>
<div class="col-md-4">
<input id="firstname" name="firstname" type="text" placeholder="First Name" class="form-control input-md">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="lastname">Last Name</label>
<div class="col-md-4">
<input id="lastname" name="lastname" type="text" placeholder="Last Name" class="form-control input-md">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="dob">Date of birth</label>
<div class="col-md-4">
<input id="dob" name="dob" type="text" placeholder="Date of birth" class="form-control input-md">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="age">Age</label>
<div class="col-md-4">
<input id="age" name="age" type="text" placeholder="Age" class="form-control input-md" disabled>
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label" for="sex">Sex</label>
<div class="col-md-4">
<label class="radio-inline"><input type="radio" name="sex" value="Male">Male</label>
<label class="radio-inline"><input type="radio" name="sex" value="Female">Female</label>
</div>
</div>
<!-- Select Basic -->
<div class="form-group">
<label class="col-md-4 control-label" for="subjects">Subjects</label>
<div class="col-md-4">
<select id="subjects" name="subjects" class="form-control">
<option value="1">Database</option>
<option value="2">ADA</option>
<option value="3">Networking</option>
</select>
</div>
</div>
<!-- Textarea -->
<div class="form-group">
<label class="col-md-4 control-label" for="localaddress">Local Address</label>
<div class="col-md-4">
<textarea class="form-control" id="localaddress" name="localaddress"></textarea>
</div>
</div>
<!-- Multiple Checkboxes (inline) -->
<div class="form-group">
<label class="col-md-4 control-label" for="localaddresscheckbox">Permenant address</label>
<div class="col-md-4">
<label class="checkbox-inline" for="localaddresscheckbox">
<input type="checkbox" name="localaddresscheckbox" id="localaddresscheckbox" value="1">
Copy Local Address to permanent Address
</label>
</div>
</div>
<!-- Textarea -->
<div class="form-group">
<label class="col-md-4 control-label" for="permenantaddress">Permenant Address</label>
<div class="col-md-4">
<textarea class="form-control" id="permenantaddress" name="permenantaddress"></textarea>
</div>
</div>
<!-- Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="submit"></label>
<div class="col-md-4">
<button id="submit" name="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</fieldset>
</form>
</div>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>
<script src="js/bootstrap-datepicker.js"></script>
<script src="js/jquery.validate.min.js"></script>
<script>
(function() {
jQuery.validator.addMethod("lettersonly", function(value, element) {
return this.optional(element) || /^[a-z]+$/i.test(value);
}, "Letters only please");
$("#regform").validate({
rules: {
dob: "required",
localaddress: "required",
permenantaddress: "required",
firstname: {
lettersonly: true,
required: true
},
lastname: {
lettersonly: true,
required: true
}
},
submitHandler: function(form) {
form.submit();
}
});
//init datepicker
$('#dob').datepicker({
'format': 'yyyy-mm-dd',
'autoclose': true
});
//copy localaddress to permenant address on checkbox click
$('#localaddresscheckbox').click(function(){
if($(this).is(':checked')) {
var localaddress = $('#localaddress').val();
$('#permenantaddress').val(localaddress); //copy local address to permenant address box
}
else {
$('#permenantaddress').val('');
}
});
//age handler
$('#dob').datepicker().on('changeDate', function (ev) {
//get current date
var today = new Date();
var currentYear = today.getFullYear(); //current year
var selectedYear = $(this).val().split('-')[0]; //selected dob year
var age = Number(currentYear) - Number(selectedYear);
$('#age').val(age);
});
})();
</script>
</body>
</html>
now the data from the local address is not being copied to the permanent address.
The server side code is as follows:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#page import="java.sql.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
String firstname=request.getParameter("firstname");
System.out.println("First name="+firstname);
String lastname=request.getParameter("lastname");
System.out.println("Last name="+lastname);
String dob=request.getParameter("dob");
System.out.println("Date of Birth="+dob);
String age=request.getParameter("age");
System.out.println("Age="+age);
String sex=request.getParameter("sex");
System.out.println("Sex="+sex);
String subjects=request.getParameter("subjects");
System.out.println("Subject="+subjects);
String localaddresscheckbox=request.getParameter("localaddresscheckbox");
System.out.println("Local Address="+localaddresscheckbox);
String permanentaddress=request.getParameter("permanentaddress");
System.out.println("Permanent Address="+permanentaddress);
try
{
//System.out.println(0);
//Class.forName("oracle.jdbc.driver.OracleDriver");
Class.forName("oracle.jdbc.driver.OracleDriver");
System.out.println(1);
Connection con=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","Subhankar","oracle07");
System.out.println(2);
Statement st= con.createStatement();
//String sql = "INSERT INTO STUDENT_DETAILS VALUES (firstname,lastname,dob,age,sex,subjects,localaddresscheckbox,permanentaddress)";
String sql="INSERT INTO STUDENT_DETAILS (first_name,last_name,date_of_birth,age,sex,subject,local_address,permanent_address) VALUES ('"+firstname+"','"+lastname+"','"+dob+"','"+age+"','"+sex+"','"+subjects+"','"+localaddresscheckbox+"','"+permanentaddress+"')";
st.executeUpdate(sql);
//
//ResultSet rs=st.executeQuery("select * from studentdetails where studentid="+studentId);
}catch(Exception e)
{
e.printStackTrace();
}
%>
</body>
</html>
You have not set the action attribute.
If you want to submit form to the same page Use
action="<?php echo $_SERVER['REQUEST_URI'] ?>"

display two different forms using value from dropdown

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>

error Uncaught SyntaxError: Unexpected token <

i want to create a form which has 2 dropdown, the second dropdown will be trigger by the first dropdown without reload the page, after the first dropdown selected/change, so i decide to use ajax
instead trigger the second dropdown it is returning this error
Uncaught SyntaxError: Unexpected token < add_product.php:1
error on above happen if i use google chrome
and this the error when i use firefox with firebug
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in /opt/lampp/htdocs/portofolio1/dd-multiple.php on line 15
Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, null given in /opt/lampp/htdocs/portofolio1/dd-multiple.php on line 16
{"data":null}
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
script.js (line 34, col 26)
this is script.js file
function AjaxFunction(id1,id2)
{
alert(id1);
var httpxml;
try
{
// Firefox, Opera 8.0+, Safari
httpxml=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
httpxml=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
httpxml=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}
function stateck(){
if(httpxml.readyState===4)
{
var myarray = JSON.parse(httpxml.responseText);
// Before adding new we must remove previously loaded elements
for(j=document.getElementById(id2).length-1;j>=0;j--)
{
document.getElementById(id2).remove(j);
}
for (i=0;i<myarray.data.length;i++)
{
var optn = document.createElement("OPTION");
optn.text = myarray.data[i].subcategory;
//optn.value = myarray.data[i].subcat_id; // You can change this to subcategory
optn.value = myarray.data[i].subcategory;
document.getElementById(id2).options.add(optn);
}
}
}
var str='';
var s1ar=document.getElementById(id1);
for (i=0;i< s1ar.length;i++) {
if(s1ar[i].selected){
str += s1ar[i].value + ',';
}
}
//alert (s1ar);
var str=str.slice(0,str.length -1); // remove the last coma from string
//alert(str);
/////
//alert(str);
var url="dd-multiple.php";
url=url+"?cat_id="+str;
url=url+"&sid="+Math.random();
//alert(url);
httpxml.onreadystatechange=stateck;
httpxml.open("GET",url,true);
httpxml.send(null);
}
this my add_product.php file
<?php
require_once './model/functions.php';
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link href="css/bootstrap.min.css" rel="stylesheet"/>
</head>
<body>
<div class="container">
<div class="row">
<div class="center-block" style="width: 130px;">
<h3><strong>Add Book</strong></h3>
</div>
</div>
<form method="post" action="" class="form-horizontal">
<div class="form-group">
<label for="kategori" class="col-lg-4 control-label">Kategori : </label>
<div class="col-lg-6">
<input type="text" class="form-control" id="kategori" name="kategori" placeholder="pilih kategori">
</div>
</div>
<div class="form-group">
<label for="tipeIklan" class="col-lg-4 control-label">Tipe Iklan : </label>
<div class="col-lg-6">
<label class="radio-inline">
<input type="radio" name="genderRadioOptions" id="tipeIklan" value=1>Dicari
</label>
<label class="radio-inline">
<input type="radio" name="genderRadioOptions" id="tipeIklan" value=0>Dijual
</label>
<label class="radio-inline">
<input type="radio" name="genderRadioOptions" id="tipeIklan" value=2>Disewakan
</label>
<label class="radio-inline">
<input type="radio" name="genderRadioOptions" id="tipeIklan" value=3>Jasa
</label>
</div>
</div>
<div class="form-group">
<label for="judul" class="col-lg-4 control-label">Judul : </label>
<div class="col-lg-6">
<input type="text" class="form-control" id="judul" name="judul" placeholder="Judul iklan anda">
</div>
</div>
<div class="form-group">
<label for="deskripsi" class="col-lg-4 control-label">Deskripsi : </label>
<div class="col-lg-6">
<textarea id="deskripsi" class="form-control" rows="5"></textarea>
</div>
</div>
<div class="form-group">
<label for="harga" class="col-lg-4 control-label">Harga(Rp.) : </label>
<div class="col-lg-3">
<input type="text" class="form-control" id="harga" name="harga" aria-describedby="helpBlock" placeholder="cukup tuliskan angka">
<span id="helpBlock" class="help-block">Contoh: 2000</span>
</div>
</div>
<div class="form-group">
<label for="kondisi" class="col-lg-4 control-label">Kondisi : </label>
<div class="col-lg-6">
<label class="radio-inline">
<input type="radio" name="genderRadioOptions" id="kondisi" value=0>Bekas
</label>
<label class="radio-inline">
<input type="radio" name="genderRadioOptions" id="kondisi" value=1>Baru
</label>
</div>
</div>
<div class="form-group">
<label for="provinsi" class="col-lg-4 control-label">Provinsi : </label>
<div class="col-lg-3">
<select id="provinsi" name="s1[]" class="form-control" onchange="AjaxFunction('provinsi', 'kota')">
<option>select one</option>
<?php
$provinsi_set = find_all_province();
while($provinsi = mysqli_fetch_assoc($provinsi_set)){
?>
<option value="<?php echo $provinsi["id"];?>"><?php echo $provinsi["nama"]; ?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="form-group">
<label for="kota" class="col-lg-4 control-label">Kota : </label>
<div class="col-lg-3">
<select id="kota" name="s2[]" class="form-control">
</select>
</div>
</div>
<div class="form-group">
<label for="foto" class="col-lg-4 control-label">Upload Foto : </label>
<div class="col-lg-6">
<img src="uploads/raditya.jpg" alt="" width="140" height="140" class="img-thumbnail">
<img src="uploads/Kambing_Jantan_buku_2.jpg" alt="" width="140" height="140" class="img-thumbnail">
<img src="uploads/raditya.jpg" alt="" width="140" height="140" class="img-thumbnail">
</div>
</div>
<div class="col-lg-offset-4">
<button type="button" id="registrationbutton" class="btn btn-default">Tayangkan!</button>
</div>
</form>
</div>
<script src="jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/script.js"></script>
<?php close_connection(); ?>
</body>
</html>
the problem dissapear when i remove this code onchange="AjaxFunction('provinsi', 'kota')"
and this is my dd-multiple.php in case someone asking for it
<?php
#$cat_id=$_GET['cat_id'];
$mn=split(",",$cat_id); // creating array
while (list ($key, $val) = each ($mn)) {
if(!is_numeric($val)){ // checking each element
echo "Data Error ";
exit;
}
}
global $id_mysql;
$query = "SELECT nama,id FROM KOTA WHERE id_prov IN ($cat_id)";
$row = mysqli_query($id_mysql, $query);
$result = mysqli_fetch_assoc($row);
$main = array('data'=>$result);
echo json_encode($main);
?>
The reason you get that error is because your mysqli_query is incorrect.
You have your link which is null. Your link should be the connection to your database, ie:
$link = mysqli_connect("localhost", "my_user", "my_password", "database");
$query = "SELECT nama,id FROM KOTA WHERE id_prov IN ($cat_id)";
$row = mysqli_query($link, $query);
$result = mysqli_fetch_assoc($row);
$main = array('data'=>$result);
echo json_encode($main);

Categories