I want to make an <input type="text"></input>put text from database when select box selected. here is my jQuery code
<script type="text/javascript" src="jquery.js"></script>
<script>
$(document).ready(function() {
$('#noID').change(function() {
var noID = $(this).val();
$.ajax({
type: 'POST',
url: 'ambilusername.php',
data: 'noID=' + noID,
success: function(response) {
$('#username').val(response);
}
});
});
});
</script>
and here is my "ambilusername.php"
<?php
include "../include/koneksi_db.php";
$noID = $_POST["noID"];
$username = mysql_query("SELECT * FROM booking_tamu WHERE noID='$noID'");
while($k = mysql_fetch_array($username)){
echo "$k[email]";
}
?>
here is my full index.php code :
<?php
include "../include/koneksi_db.php";
?>
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script>
$(document).ready(function() {
$('#noID').change(function() {
var noID = $(this).val();
$.ajax({
type: 'POST',
url: 'ambilusername.php',
data: 'noID=' + noID,
success: function(response) {
$('#username').val(response);
}
});
});
});
</script>
</head>
<body>
<form method="post" action="?page=prosesTambahAkun">
<table class="table-data" width=100% border=1>
<tr><td colspan="2" class="head-data">Tambah Data Akun</td></tr>
<tr>
<td class="pinggir-data">ID Pemesan</td>
<td>
<select name="noID" id="noID" required>
<option value="">------Pilih ID Pemesan------</option>
<?php
$query = "SELECT no_booking, COUNT(no_booking) AS 'jumlah' FROM booking_tamu GROUP BY no_booking ASC";
$hasil = mysql_query($query);
while ($data = mysql_fetch_array($hasil)){
echo "<option value='".$data['no_booking']."'>".$data['no_booking']."</option>";
}
?>
</select>
</td>
</tr>
<tr>
<td class="pinggir-data">Username</td>
<td>
<input type="text" id="username" name="username" size="30px" readonly></input>
</td>
</tr>
<tr><td colspan="2" align="center" class="head-data">
<input type="submit" value="Tambah" name="tambah">
</td></tr>
</table>
</form>
</body>
</html>
the problem is when i select the value on select box, the textbox doesn't put something on it. can you please help me?
The problem is the naming of your table column:
change this:
$username = mysql_query("SELECT * FROM booking_tamu WHERE noID='$noID'");
to this:
$username = mysql_query("SELECT * FROM booking_tamu WHERE no_booking='$noID'");
Related
I am not really good in coding, I need a help with my code. I have a code to search in a database. Now it's showing all the data on the database, when somebody search, it will filter out and show me result on the same table.I only want to show the result, when somebody search on the search bar, it should show me the filtered data. otherwise, my table should be hidden.
Can anybody please tell me how to do that. Thank you so much for your time.
<?php
if(isset($_POST['search']))
{
$valueToSearch = $_POST['valueToSearch'];
// search in all table columns
// using concat mysql function
$query = "SELECT * FROM `ADDRESS` WHERE CONCAT(`ID`, `STATE`) LIKE '%".$valueToSearch."%'";
$search_result = filterTable($query);
}
else {
$query = "SELECT * FROM `ADDRESS`";
$search_result = filterTable($query);
}
// function to connect and execute the query
function filterTable($query)
{
$connect = mysqli_connect("localhost:3306", "root", "dbadmin", "simplymac");
$filter_Result = mysqli_query($connect, $query);
return $filter_Result;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>SimplyMac PO Tracking Tool</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<style>
</style>
</head>
<body>
<div class="images-wrapper">
<img class="Large" src="/dbadmin/Images/simplymac_logo.png" width="320" height="140" />
</div>
<form action="index.php" method="post">
<div class="wrap">
<center><h3>PO TRACKING TOOL</h3></center>
<center><table>
<tr>
<td><input type="text" name="valueToSearch" placeholder="Enter Purchase Order (PO#) Number" size="100" class="searchbar"></td>
<td><input type="submit" name="search" value="SEARCH" class="Button"></td>
</tr>
</table></center>
</div>
<table class="resultdata">
<tr>
<th>ID</th>
<th>ADDRESS_LINE_1</th>
<th>ADDRESS_LINE_2</th>
<th>CITY</th>
<th>STATE</th>
<th>ZIP</th>
</tr>
<?php while($row = mysqli_fetch_array($search_result)):?>
<tr>
<td><?php echo $row['ID'];?></td>
<td><?php echo $row['ADDRESS_LINE_1'];?></td>
<td><?php echo $row['ADDRESS_LINE_2'];?></td>
<td><?php echo $row['CITY'];?></td>
<td><?php echo $row['STATE'];?></td>
<td><?php echo $row['ZIP'];?></td>
</tr>
<?php endwhile;?>
</table>
</form>
</body>
</html>
You can use ajax for your problem.
When customer type in text box at that time call one java script function, in this function get text box value and call ajax for result table.
function getResult(search)
{
var file_path = '';//your php file path
$.ajax({
type: "POST",
url: file_path,
data: search,
cache: false,
success: function(result){
//print result in one div
}
});
}
<input type="submit" name="search" value="SEARCH" class="Button" onClick="getResult(this.value);">
We have a .aspx page with two HTML SELECT element and we want to load countries in one dropdownlist and load cities of a country in the other.
we are using entity framework to access data.
I tried PageMethods and &Ajax but I could not access my city dropdown from within a static web method. this is what we have so far:
<!-- Signup.aspx-->
<select id="cmb_Region" runat="server" onchange="GetCitiesOfRegion();" datatextfield="region_title" datavaluefield="region_id"></select>
<select runat="server" id="cmb_City" datatextfield="city_title" datavaluefield="city_id" class="ui dropdown"></select>
<script type="text/javascript">
function GetCitiesOfRegion(regionId)
{
$.ajax({
url:"Signup.aspx/GetCities",
type:"POST",
data:'{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
alert("success");
}
});
}
</script>
and this is code-behind code:
//Signup.aspx.cs
[WebMethod]
public static List<City> GetCities(int RegionId)
{
behbimeh_informationEntities db = new behbimeh_informationEntities();
return db.City.Where(i => i.region_id == RegionId).ToList();
}
Actually the code is not correct and I dont know how to pass the cmb_region selected value to the webmethod? and I dont know how to bind the cmb_city to the returned List of cities.
please share your knowledge. thanks...
To get cmb_Region value
var regionId = $('#<%= cmb_Region.ClientID %>').val();
To get cities by region and bind at client side
[WebMethod]
public static string GetCities(int RegionId)
{
behbimeh_informationEntities db = new behbimeh_informationEntities();
var cities= db.City.Where(i => i.region_id == RegionId).Select(item=>new { item.ValueField, item.TextField }).ToList();
return Newtonsoft.Json.JsonConvert.SerializeObject(cities);
}
<script type="text/javascript">
function GetCitiesOfRegion(regionId)
{
$.ajax({
url:"Signup.aspx/GetCities",
type:"POST",
data:'{"RegionId":'+regionId+'}',
success: function (r) {
var cities=JSON.parse(r.d);
var citiesOptions="";
for(var i=0;i<cities.length;i++){
citiesOptions+='<option value="'+cities[i].Value+'">'+cities[i].Text+'</option>';
}
$('#<%= cmb_City.ClientID %>').html(citiesOptions);
}
});
}
first you will need to clear the existing data, like so:
$('#cmb_city').empty();
next, you need to load the returned list to your ddl.
$.ajax({
url:"Signup.aspx/GetCities",
type:"POST",
data:'{"RegionId":'+$('#cmb_Region').val()+'}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
$.each(r, function() {
$('#cmb_city').append($('<option>').text(this.Name).attr('value', this.Id));
});
}
});
where Name and Id are your text and value fields respectively.
you will also probably need to send the selected region.
Here is your answer like how to bind data from database using Ajax in php
<!-- edit.php -->
<?php
include("config.php");
$id=$_REQUEST['id'];
echo $id;
$query=mysqli_query($con,"SELECT * FROM register r
INNER JOIN country c ON r.cuid = c.cuid
INNER JOIN state s ON r.sid = s.sid
INNER JOIN city ct ON r.cid = ct.cid where id='$id'");
while($r=mysqli_fetch_array($query))
{
$fn=$r['firstname'];
$add=$r['address'];
$gn=$r['gender'];
$hobby=$r['hobby'];
$h=explode(',',$hobby);
$q=array('reading','traveling','cricket','drawing');
$country=$r['cuid'];
$state=$r['sid'];
$city=$r['cid'];
echo $gn;
$edu= $r['education'];
$email=$r['email'];
$pass=$r['password'];
$conpass=$r['conpassword'];
$phno=$r['phoneno'];
}
?>
<html>
<head>
<script src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#country').on('change',function(){
var countryID = $(this).val();
if(countryID){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'cuid='+countryID,
success:function(html){
$('#state').html(html);
$('#city').html(html);
}
});
}else{
$('#state').html(html);
$('#city').html(html);
}
});
$('#state').on('change',function(){
var stateID = $(this).val();
if(stateID){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'sid='+stateID,
success:function(html){
$('#city').html(html);
}
});
}else{
$('#city').html(html);
}
});
});
</script>
</head>
<body>
<form method="post" action="update.php">
<table border="1" align="center">
<caption>Edit user data</caption>
<tr>
<td>First name</td>
<td><input type="text" name="fn" value="<?php echo $fn;?>"></td>
</tr>
<tr>
<td>Address</td>
<td><input type="text" name="add" value="<?php echo $add;?>"></td>
</tr>
<tr>
<td>Gender</td>
<td><input type="radio" name="gn" value="male" <?php echo ($gn=='male')?'checked':'' ; ?> size="17">Male
<input type="radio" name="gn" value="female" <?php echo ($gn=='female')?'checked':'' ; ?> size="17">Female
</td>
</tr>
<tr>
<td>Hobby</td>
<td><input type="checkbox" name="hobby[]" value="reading" <?php if(in_array('reading',$h)){echo ("checked:'checked'");}?> >reading
<input type="checkbox" name="hobby[]" value="traveling" <?php if(in_array('traveling',$h)){echo ("checked:'checked'");}?> >traveling
<input type="checkbox" name="hobby[]" value="cricket" <?php if(in_array('cricket',$h)){echo ("checked:'checked'");}?> >cricket
<input type="checkbox" name="hobby[]" value="drawing" <?php if(in_array('drawing',$h)){echo ("checked:'checked'");}?> >drawing</td>
</tr>
<?php
$query = mysqli_query($con,"SELECT * FROM country");
//Count total number of rows
$rowCount = mysqli_num_rows($query);
?>
<td>Country</td>
<td><select name="country" id="country">
<option value="<?php echo $country;?>"><?php echo $country;?></option>
<?php
if($rowCount > 0)
{
while($row = mysqli_fetch_array($query))
{
echo '<option value="'.$row['cuid'].'">'.$row['country'].'</option>';
}
}
else
{
echo '<option value="">Country not available</option>';
}
?>
</select>
</td></tr>
<tr>
<td>State</td>
<td>
<select name="state" id="state">
<option value="<?php echo $state;?>"><?php echo $state;?></option>
</select>
</td></tr>
<tr>
<td>City</td>
<td>
<select name="city" id="city">
<option value="<?php echo $city;?>"><?php echo $city;?></option>
</select>
</td>
</tr>
<tr>
<td>Education</td>
<td><input type="text" name="edu" value="<?php echo $edu;?>"></td>
</tr>
<td>Email</td>
<td><input type="text" name="email" value="<?php echo $email;?>"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="text" name="pass" value="<?php echo $pass;?>"></td>
</tr>
<tr>
<td>Confirm password</td>
<td><input type="text" name="conpass" value="<?php echo $conpass;?>"></td>
</tr>
<tr>
<td>Phone no</td>
<td><input type="text" name="phno" value="<?php echo $phno;?>"></td>
</tr>
<tr>
<td><input type="hidden" name="id" value="<?php echo $id;?>">
<input type="submit" name="update" value="update"></td>
</tr>
</table>
</form>
</body>
</html>
--------------------
<!--ajaxData.php-->
<?php
//Include database configuration file
include("config.php");
if(isset($_POST["cuid"]) && !empty($_POST["cuid"]))
{
//Get all state data
$query = mysqli_query($con,"SELECT * FROM state WHERE cuid = ".$_POST['cuid']."");
//Count total number of rows
$rowCount = mysqli_num_rows($query);
//Display states list
if($rowCount > 0)
{
echo '<option value="">Select state</option>';
while($row = mysqli_fetch_array($query))
{
echo '<option value="'.$row['sid'].'">'.$row['state'].'</option>';
}
}
else
{
echo '<option value="">State not available</option>';
}
}
if(isset($_POST["sid"]) && !empty($_POST["sid"]))
{
//Get all city data
$query = mysqli_query($con,"SELECT * FROM city WHERE sid =".$_POST['sid']."");
//Count total number of rows
$rowCount = mysqli_num_rows($query);
//Display cities list
if($rowCount > 0)
{
echo '<option value="">Select city</option>';
while($row = mysqli_fetch_array($query))
{
echo '<option value="'.$row['cid'].'">'.$row['city'].'</option>';
}
}
else
{
echo '<option value="">City not available</option>';
}
}
?>
This question already has answers here:
How can I bind an array of strings with a mysqli prepared statement?
(7 answers)
Closed 11 months ago.
Good day, I've seen a couple of threads with similar questions but I can't seem to implement the suggestions on my practice project.
is there any way I can add a function where my selected items can be deleted at once?
Here are my codes.
select.php
<?php
$connect = mysqli_connect("localhost", "root", "root", "appointments");
$output = '';
$sql = "SELECT * FROM appointments ORDER BY id DESC";
$result = mysqli_query($connect, $sql);
$output .= '
<div class="table-responsive">
<table class="table table-bordered">
<tr>
<th width="5%">Checkbox</th>
<th width="10%">Id</th>
<th width="40%">Name</th>
<th width="40%">Email</th>
<th width="40%">Address</th>
<th width="10%">phoneNumber</th>
<th width="10%">appointmentTime</th>
<th width="10%">appointmentDate</th>
<th width="50%">message</th>
<th width="10%">delete</th>
</tr>';
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
</td>
<td><input type="checkbox" /></td>
<td>'.$row["id"].'</td>
<td class="name" data-id1="'.$row["id"].'" contenteditable>'.$row["name"].'</td>
<td class="email" data-id2="'.$row["id"].'" contenteditable>'.$row["email"].'</td>
<td class="address" data-id2="'.$row["id"].'" contenteditable>'.$row["address"].'</td>
<td class="phoneNumber" data-id2="'.$row["id"].'" contenteditable>'.$row["phoneNumber"].'</td>
<td class="appointmentTime" data-id2="'.$row["id"].'" contenteditable>'.$row["appointmentTime"].'</td>
<td class="appointmentDate" data-id2="'.$row["id"].'" contenteditable>'.$row["appointmentDate"].'</td>
<td class="message" data-id2="'.$row["id"].'" contenteditable>'.$row["message"].'</td>
<td><button type="button" name="delete_btn" data-id3="'.$row["id"].'" class="btn btn-danger btn_delete">Delete</button></td>
</tr>
';
}
}
else
{
$output .= '<tr>
<td colspan="10"><center><p style="color:red">No Data Found</p></center></td>
</tr>';
}
$output .= '</table>
</div>';
echo $output;
?>
Here's the delete function for a single row.
<?php
$connect = mysqli_connect("localhost", "root", "root", "appointments");
$sql = "DELETE FROM appointments WHERE id = '".$_POST["id"]."'";
if(mysqli_query($connect, $sql))
{
echo 'Data Deleted';
}
?>
Here's my display page.
<?php
require("config.php");
if(empty($_SESSION['user']))
{
header("Location: success.php");
die("Redirecting to index.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">
<meta name="description" content="">
<meta name="author" content="">
<title>Simple Sidebar - Start Bootstrap Template</title>
<!-- Bootstrap Core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="css/simple-sidebar.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
<div id="wrapper">
<!-- Sidebar -->
<div id="sidebar-wrapper">
<ul class="sidebar-nav">
<li class="sidebar-brand">
<a href="#">
Hope Medi Clinic
</a>
</li>
<li>
Logout
</li>
<li>
Main Website
</li>
</ul>
</div>
<!-- /#sidebar-wrapper -->
<!-- Page Content -->
<div class="container">
<br />
<br />
<br />
<div class="table-responsive">
<h3 align="center">Appointments</h3><br />
<div id="live_data"></div>
Toggle Menu
</div>
</div>
<!-- /#page-content-wrapper -->
</div>
<script>
$(document).ready(function(){
function fetch_data()
{
$.ajax({
url:"select.php",
method:"POST",
success:function(data){
$('#live_data').html(data);
}
});
}
fetch_data();
function edit_data(id, text, column_name)
{
$.ajax({
url:"edit.php",
method:"POST",
data:{id:id, text:text, column_name:column_name},
dataType:"text",
success:function(data){
alert(data);
}
});
}
/* ............. */
$(document).on('blur', '.name', function(){
var id = $(this).data("id1");
var name = $(this).text();
edit_data(id, name, "name");
});
$(document).on('blur', '.email', function(){
var id = $(this).data("id2");
var email = $(this).text();
edit_data(id, email, "email");
});
$(document).on('blur', '.address', function(){
var id = $(this).data("id2");
var address = $(this).text();
edit_data(id, address, "address");
});
$(document).on('blur', '.phoneNumber', function(){
var id = $(this).data("id2");
var phoneNumber = $(this).text();
edit_data(id, phoneNumber, "phoneNumber");
});
$(document).on('blur', '.appointmentTime', function(){
var id = $(this).data("id2");
var appointmentTime = $(this).text();
edit_data(id, appointmentTime, "appointmentTime");
});
$(document).on('blur', '.appointmentDate', function(){
var id = $(this).data("id2");
var appointmentDate = $(this).text();
edit_data(id, appointmentDate, "appointmentDate");
});
$(document).on('blur', '.message', function(){
var id = $(this).data("id2");
var message = $(this).text();
edit_data(id, message, "message");
});
$(document).on('click', '.btn_delete', function(){
var id=$(this).data("id3");
if(confirm("Are you sure you want to delete this?"))
{
$.ajax({
url:"delete.php",
method:"POST",
data:{id:id},
dataType:"text",
success:function(data){
alert(data);
fetch_data();
}
});
}
});
});
</script>
</body>
</html>
It will be cleaner and more professional to send an array of ids to your php file as suggested by earlier answers:
<input name="ids[]" value="<?php echo $id; ?>" type="checkbox">
...then make just one trip to the database to delete multiple rows.
if (
empty($_POST['ids'])
// || array_filter($_POST['ids'], function($v) { return !ctype_digit($v); })
) {
exit('Missing/Invalid data submitted'); // be deliberately vague
}
$connect = new mysqli("localhost", "root", "root", "appointments");
$count = count($_POST['ids']);
$stmt = $connect->prepare(
sprintf(
"DELETE FROM appointments WHERE id IN (%s)",
implode(',', array_fill(0, $count, '?')) // e.g if 3 ids, then "?,?,?"
)
);
$stmt->bind_param(str_repeat('i', $count), ...$_POST['ids']);
$stmt->execute();
printf('Deleted %d row(s)', $stmt->affected_rows());
This resembles a similar post of mine: SELECT with dynamic number of values in IN()
I'm not sure exactly how you are sending the data from the HTML to the PHP page in this example, so I will give you a generic simple implementation and hopefully you can figure out how to work it into your project.
HTML:
Using checkboxes, you can send multiple values as an array to a php script like so.
<form action="delete.php" method="POST">
<input name="delete[]" value="id_of_row" type="checkbox">
<input name="delete[]" value="id_of_another_row" type="checkbox">
<button type="submit">Submit</button>
</form>
This will send an array of whatever is in the value attribute of each box that is checked. You would then be able to delete every row that was checked with the following php script.
PHP:
<?php
$connect = mysqli_connect("localhost", "root", "root", "appointments");
foreach($_POST['delete'] as $id){
$sql = "DELETE FROM appointments WHERE id = '" . $id . "';
if(mysqli_query($connect, $sql))
{
echo 'Data Deleted';
}
}
?>
This should be what you need to somehow implement into your existing project so that you can delete multiple rows at once.
You should be using array for this.
<td><input type="checkbox" name='check[]' value=".$row['id']." /></td>
and in delete function you should be doing something like this.
<?php
$connect = new mysqli("localhost", "root", "root", "appointments");
$totalCheckboxChecked = sizeof($_POST['check']);
for($i=0;$i<$totalCheckboxChecked;$i++)
{
$idToDelete = $check[$i];
$sql = "DELETE FROM appointments WHERE id = $idToDelete";
$result=$connect->query($sql);
}
I am trying to figure out how to submit button with two actions based on dropdown list that I get from MySQL. One is for updating to database and then proceed to nextpage while the other actions is to proceed to specific page. I've tried all the solution but most of them only has a few dropdown menu, mine have 40 menus.
This is my JavaScript
<script type='text/javascript'>
$(window).load(function(){
//$(document).ready(function() {
<!--To Enable button "MULA"-->
$('#lst_respon').change(function() {
if ($(this).find(":selected").val()!='11') {
$('#button').attr('disabled',true);
} else {
$('#button').removeAttr('disabled');
}
});
$('#lst_respon').change(function()
{
$('#form1').submit();
});
});
function changeTextBox()
{
var val=$('#lst_respon').val();
if(val==='11')
{
$('#value').prop('disabled', true);
}
else{$('#value').removeAttr("disabled");}
}
</script>
And this is my HTML
<div align="center">
<table width="60%" border="1" class="zui-table">
<thead>
<tr>
<th colspan="3" align="center">Status</th>
</tr>
</thead>
<tr>
<?php
$smt = $conn->prepare('select * From lookup_caraterima');
$smt->execute();
$data = $smt->fetchAll();
$smt2 = $conn->prepare('select * From lookup_kodrespon');
$smt2->execute();
$data2 = $smt2->fetchAll();
?>
<td width="253">Cara Terima</td>
<td width="5">:</td>
<td width="164">
<select name="lst_cterima" id="lst_cterima">
<?php foreach ($data as $row): ?>
<option value="<? echo $row["kodterima"];?>"><? echo $row["jenis"];?>
</option>
<?php endforeach ?>
</select>
</td>
</tr>
<tr>
<td>Kod Respon</td>
<td>:</td>
<td>
<select name="lst_respon" id="lst_respon" onchange="changeTextBox()">
<?php foreach ($data2 as $row2): ?>
<option value="<? echo $row2["kod"];?>"><? echo $row2["kod"].'- '.$row2 ["Keterangan"];?></option>
<?php endforeach ?>
</select></td>
</tr>
<tr>
<td><label for ="sebab">Sebab</label></td>
<td>:</td>
<td><input type="textbox" id="value" size="100" disabled</td>
</tr>
<tr>
<td colspan="3" align="center"><form name="form1" method="post" action="main.php?load=4&SerialID=<?php echo $noSiri; ?>&month=<?php echo $monthA;?>&year=<?php echo $yearA;?>&tab=A">
<input type="submit" name="button" id="button" value="Teruskan" class="myButton">
</form></td>
</tr>
</table>
</div>
For an automated solution to submit a form based a dropdown selection, you could try using the data attribute, something like:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<form id="tester">
<select name="test">
<option value="best" data-instructions='<?php echo json_encode(array('action'=>'page1')); ?>'>Best</option>
<option value="rest" data-instructions='<?php echo json_encode(array('action'=>'page2')); ?>'>Rest</option>
<option value="guest" data-instructions='<?php echo json_encode(array('action'=>'page3')); ?>'>Guest</option>
<option value="lest" data-instructions='<?php echo json_encode(array('action'=>'page4')); ?>'>Lest</option>
</select>
<input type="submit" name="submit" value="SUBMIT" />
</form>
<script>
$(document).ready(function() {
$('#tester').submit(function(e) {
// Stop form from submitting
e.preventDefault();
// Get the select dropdown
var thisSelect = $(this).find('select[name=test]');
// Get the value
var thisVal = thisSelect.val();
// Get the options separately
var thisOpts = thisSelect.children();
// Create a holder
var thisData = {};
// Loop through the options
$.each(thisOpts,function(k,v) {
// Get the current value
var currVal = $(v).attr('value');
// If the current value is the same as the value selected
if(currVal == thisVal) {
// Get the instructions from the option
thisData = $(v).data('instructions');
// Stop looping
return false
}
});
console.log(thisData);
});
});
</script>
On submission, the selection will give you an object that you can use to instruct how to submit the form:
// thisData.action
{action: "page2"}
i want call the same ajax function for multiple buttons please help me the code is given below. this code will generate buttons and when we click on the buttons it prints the details ...please solve. This code will generate buttons in table.
<head>
<script>
$(document).ready(function()
{
$("#save").click(function()
{
var sel = $("#response").val();
var fudate=$("#fdate").val();
var cmd=$("#cm").val();
var id=$("#id").val();
$.ajax(
{
type: "POST",
url: "autosave.php",
data: {response:sel,fdate:fudate,cm:cmd,id:id},
success: function(result)
{
alert('result');
$a= $("#ak").html(result);
}
});
});
});
</script>
</head>
<body>
<div id="company_details">
<div id="ak"></div>
<table border="1" align="left">
<tr>
<th >Company</th>
<th>Contact Person</th>
<th>Contact Person's No.</th>
<th>HR</th>
<th>HR's No.</th>
<th>Current Vacancies</th>
<th>Response</th>
<th>Follow Up Date</th>
<th>Comment</th>
<th></th>
<th>Edit</th>
</tr>
<?php
$con=mysql_connect("localhost","root") or die("Error In Connection:-".mysql_error());
mysql_select_db("ttcs",$con) or die("Error In DB Selection:-".mysql_error());
$sql="select * from company_details";
$rs=mysql_query($sql) or die(mysql_error());
while($row=mysql_fetch_array($rs))
{
?>
<tr>
<td>
<input type="text" name="name" value= <?php $e=$row[0];echo $row[1];?>></td>
<td><input type="text" name="cp" value= <?php echo $row[7]; ?>></td>
<td><input type="text" name="cpn" value= <?php echo $row[9]; ?>></td>
<td><input type="text" name="hr" value= <?php echo $row[10]; ?>></td>
<td><input type="text" name="hrn" value= <?php echo $row[12]; ?>></td>
<td>
<?php
$sql2="select * from vacancies where company_id='$e'";
$rs2=mysql_query($sql2);
if($rs2)
{
while($row2=mysql_fetch_array($rs2))
{?>
<textarea name="cv" value=<?php echo $row2[1];?>></textarea>
<?php }}?>
</td>
<td>
<select name="response" id="response">
<option value="Not interested">Not Interested</option>
<option value="Not responding">Not Responding</option>
<option value="follow up">Follow up</option>
<option value="Interested">Interested</option>
</select></td>
<?php
$sql1="select * from call_details_company where company_id=$row[0]";
$rs1=mysql_query($sql1);
$row1=mysql_fetch_array($rs1);
?>
<input type="date" name="fdate" id="fdate" value=<?php echo $row1[3];?>>
<input type="text" name="cm" id="cm" value=<?php echo $row1[5];?>>
<button id="save" >save</button>
</td>
</tr>
<?php
}
?>
</body>
ID of an element must be unique, so within the loop don't use ID, change the id of the button to class value then use the input element's name to find the relative elements within the tr
$(document).ready(function () {
$(".save").click(function () {
var $tr = $(this).closest('tr')
var sel = $tr.find("select").val();
var fudate = $tr.find('input[name="fdate"]').val();
var cmd = $tr.find('input[name="cm"]').val();
//need to fix this selector #id too, not able to locate it in the given html structure
var id = $tr.find("#id").val();
$.ajax({
type: "POST",
url: "autosave.php",
data: {
response: sel,
fdate: fudate,
cm: cmd,
id: id
},
success: function (result) {
alert('result');
$a = $("#ak").html(result);
}
});
});
});
use like this
<script>
function ajaxCallDemo() {
var sel = $("#response").val();
var $tr = $(this).closest('tr');
var cmd = $tr.find("input[name='cm']").val();
var fudate = $tr.find("input[name='fdate']").val();
var id = $tr.find("#id").val();
$.ajax({
type: "POST",
url: "autosave.php",
data: {
response: sel,
fdate: fudate,
cm: cmd,
id: id
},
success: function(result) {
alert('result');
$a = $("#ak").html(result);
}
});
}
$(document).ready(function() {
$("#save").click(function() {
ajaxCallDemo();
});
$("#save2").click(function() {
ajaxCallDemo();
});
});
</script>