JQUERY change div contents based on select options -- I'm lost - javascript

In the following code, I have two dropdowns, unit-type and unit-size. I have two , unit-price and row-total, that need to be updated, first on page load, then whenever one or both dropdowns are changed.
The problem is that I'm new to Javascript and Jquery and really don't know what I'm doing, and none of the examples I've tried following seems to work for me. I'm hoping someone here can point me to where my problem is and how to make it work?
<?php
session_start();
include '../include/search.php';
$dbserver = '#########';
$dbname = '########';
$dbuser = '########';
$dbpassword = '#########';
$category = $_GET['category'];
$db = mysqli_connect($dbserver, $dbuser, $dbpassword, $dbname);
if (mysqli_connect_errno()) {
die("Connection failed: " . mysqli_connect_error());
}
mysqli_select_db($db, $dbname);
$sql = "SELECT * FROM products WHERE category = '".$category."'";
$result = mysqli_query($db, $sql);
if (!$result) {
die ('Error: Could not select products'.mysqli_error($db));
}
function make_size_select($product) {
echo '<select name="unit_menu">';
$price_set = array(
'halfpint'=>$product['halfpint'],
'pint'=>$product['pint'],
'dk'=>$product['dk'],
'quart'=>$product['quart']);
$handles = array(
'halfpint'=>'Half Pint (8 oz)',
'pint'=>'Pint (16 oz)',
'dk'=>'Dutch Kettle (16 oz)',
'quart'=>'Quart (32 oz)');
$i = 0;
foreach ($price_set as $key=>$value) {
if ( $value > 0.00) {
$i++;
if ($i == 1) {
echo '<option value="'.$value.'" selected="selected">'.$handles[$key].'</option>';
} else {
echo '<option value="'.$value.'">'.$handles[$key].'</option>';
}
}
}
echo '</select>';
}
function category_select($product) {
$categories = array();
foreach ($product as $row) {
if (!in_array($row['category'], $categories)) {
array_push($row['category']);
}
}
echo '<select name="categories" onChange="loadNewCategory();">';
foreach ($categories as $category) {
echo '<option '.$category.'>'.ucfirst($category);
}
echo '</select>';
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Smoky Mountain Honey House</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link href="../css/style.css" rel="stylesheet" type="text/css" media="all" />
<link href="../css/custom.css" rel="stylesheet" type="text/css" media="all" />
<link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
<script type="text/javascript" src="../js/jquery-1.9.0.min.js"></script>
<script type="text/javascript" src="../js/menu.js"></script>
</head>
<body>
<!----start-header----->
<div class="header_img">
<img src="../images/header_img.jpg" alt="" />
<div class="wrap">
<div class="header">
<div class="logo">
<img src="../images/logo.png" alt="">
</div>
<div class="menu">
<nav class="clearfix">
<ul class="clearfix">
<li class="active">HOME</li>
<li>ABOUT</li>
<li>LOCATIONS</li>
<li>SHOP</li>
<li>CONTACT</li>
</ul>
Menu
</nav>
</div>
</div>
</div>
</div>
<!----End-header----->
<div class="wrap">
<div class="content">
<div class="category-header">
<h2><?php echo ucfirst($category); ?></h2>
<!-- <div class="product-search">
<p>
Search our inventory: <form name="search" action="../include/functions.php?method=search" method="post">
<input type="text" name="search_terms" />
<input type="submit" value="submit" />
</form>
</p>
</div> -->
</div>
<?php
while ( $product = mysqli_fetch_array( $result, MYSQLI_ASSOC ) ) {
// display product ?>
<div class="product_row">
<script>
var product = <?php echo json_encode($product); ?>
</script>
<form name="order_row_<?php echo $product['product_id']; ?>" action="#" method="post">
<div class="product_id">
<input type="hidden" name="product_id" value="<?php echo $product['product_id']; ?>">
<?php echo ucfirst($product['name']); ?>
</div>
<div class="type">
<select name="unit_type">
<option value="ind" selected>By the Jar</option>
<option value="case">By the Case</option>
</select>
</div>
<div class="unit">
<?php echo make_size_select($product); ?>
</div>
<div class="unit-price">
</div>
<div class="qty">
<input type="number" name="qty" min="0" maxlength="5" max="11" label="How many?" />
</div>
<div class="row-price"></div>
<div class="add_cell">
<button class="add-to-cart" onclick="addToCart();">Add To Cart</button>
</div>
</form>
</div>
<?php }; ?>
</div>
</div>
<div class="copy-right">
<p>© 2016 Smoky Mountain Honey House</p>
</div>
</div>
<!---End-footer---->
<script>
$( ".unit_type" ).change(function () {
var unitPrice = $(this).val();
if ( $(this).closest.(".unit_type") == "ind") {
unitPrice = unitPrice / 12.00;
}
$( this ).closest.( ".unit-price" ).text( unitPrice );
})
.change();
</script>
</body>
</html>

jQuery's closest is not finding things located in siblings (or parents' siblings). I would get the closest product row and find children elements from there.
There's also a dot after each closest. For example:
closest.(".unit-price");
should actually be:
closest(".unit-price");
The element you're trying to select (.unit-type) doesn't contain a class which you're trying to find, it contains a name instead. A dot (.) in jQuery represents a class, a hash symbol (#) represents an id.
<select name="unit_type">
should be:
<select name="unit_type" class="unit_type">
if you wanna be able so select it with:
$(".unit_type");
$(".unit-type").change(function() {
var productRow = $(this).closest(".product_row");
var price = 5; // get your price here
var unitPrice;
if ($(this).val() == "ind") { // $(this).val() contains the value of the selected option
unitPrice = price / 12.00;
} else {
unitPrice = price / 24.00;
}
productRow.find(".unit-price").text(unitPrice);
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="product_row">
<div class="type">
<select name="unit_type" class="unit-type">
<option value="ind" selected>By the Jar</option>
<option value="case">By the Case</option>
</select>
</div>
<div class="unit-price">
</div>
</div>

Related

How to get the selected multiple values from checkbox and submit them in a form to get the matched search results

This form contains a dropdown list that has multiple options with checkboxes, now when a user selects 1 or more checkboxes and presses submit, the values should be processed with the matching search results. Previously, I had a select tag with an option tag that was used to get the results. Now, since I added the functionality of searching for more than one option, I added checkboxes, but now I am not sure how to get the results.
Html and Php Code
<form action="<?php the_permalink() ?>" class="ajax-search-form leaders-header" id="searchform" method="post" role="search">
<?php get_template_part( 'blocks/leaderboard/search-form' ) ?>
<div class="sort">
<body>
<?php if ($departments = get_field_object('field_5da06da87ae0f')) : ?>
<div class="sort-item">
<div id="list1" class="dropdown-check-list" tabindex="100">
<span class="anchor" style="font-size: small">All Departments</span>
<ul id="items" class="items" name="department" >
<label for="test">
<?php foreach ($departments['choices'] as $key => $department) : ?>
<input type="checkbox" name="check" id="test" value="unchecked" /> <option style="font-size: small" <?php if ( isset($_REQUEST['role']) and $_REQUEST['role'] == $key) echo 'selected' ?> value="<?php echo $key; ?>">
<?php echo $department; ?></option></label></br>
<?php endforeach; ?>
<input style="font-size: small" type="submit" value="Submit" "/>
</ul>
</div>
</div>
<?php endif ?>
</body>
JavaScript:
<script type="text/javascript">
var checkList = document.getElementById('list1');
var items = document.getElementById('items');
var isChecked = document.getElementById('items').checked;
checkList.getElementsByClassName('anchor')[0].onclick = function (evt) {
if (items.classList.contains('visible')){
items.classList.remove('visible');
items.style.display = "none";
}
else{
items.classList.add('visible');
items.style.display = "block";
}
}
items.onblur = function(evt) {
items.classList.remove('visible');
}
</script>
Problem is that every checkbox will have the same name and id so you will be not able to recognize which option belongs to which checkbox but you can try something like this
<?php foreach ($departments['choices'] as $key => $department) : ?>
<input type="checkbox" name="<?= $department ?>" id="<?= $department ?>" value="unchecked" />

Can't $_GET or $_POST Dynamic Drop Down Variables

JavaScript
// JQuery script is on ajax.php page
// JQUERY PIECE TO PROCESS STATE AND CITY VALUES
// BASED ON COUNTRY SELECTION
function change_CountryNo() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "ajax.php?CountryNo=" + document.getElementById("CountryNodd").value, false);
xmlhttp.send(null);
document.getElementById("StateID").innerHTML = xmlhttp.responseText;
if (document.getElementById("CountryNodd").value == "CountryNo") {
document.getElementById("CityID").innerHTML = "<select><option>City</option></select>";
}
}
function change_StateID() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "ajax.php?StateID=" + document.getElementById("StateIDdd").value, false);
xmlhttp.send(null);
document.getElementById("CityID").innerHTML = xmlhttp.responseText;
if (getElementById("StateIDdd").value == "StateID") {
document.getElementById("CityID").innerHTML = "<select><option>City</option></select>";
}
}
<!DOCTYPE html>
<html>
<head>
<!-- index.php -->
<!-- THIS CODE PROVIDES A DROP DOWN FORM
FOR USER TO SELECT COUNTRY THEN STATE THEN CITY
A JQUERY SCRIPT PROCESSES THE COUNTRY VALUE
TO PRODUCE THE APPROPRIATE STATES AND
PROCESSES THE STATE VALUE TO PRODUCE
THE APPROPRIATE CITIES -->
<title>Country, State, City Selection</title>
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/styles.css">
</head>
<body>
<!-- THESE FILES ARE DATABASE CONNECTION AND FUNCTIONS
FOR VARIOUS LOGIN, USER SESSION VARIABLES TO IDENTIFY
THE CONTACT NO OF USER UPDATING THEIR LOCATION -->
<?php include("includes/header.php") ?>
<?php include("includes/nav.php") ?>
<?php //Check user's login status
if (logged_in() === false) {
echo "Redirecting...";
redirect("../index.html");
}
?>
<!-- responsive setup for form -->
<div class="row">
<div class="col-lg-6 col-lg-offset-3">
</div>
</div>
<!-- end of class row div -->
<div class="row">
<div class="col-md-6 col-md-offset-3">
<div class="panel panel-login">
<div class="panel-heading">
<div class="row">
<div class="col-xs-12">
<div class="col-xs-6">
</div>
<div class="col-xs-6">
Country-State-City Selection
</div>
</div>
<hr>
</div>
<!-- end of class row div -->
<div class="panel-body">
<div class="row col-md-12" style="text-align: center">
<form method="POST" action="<?php echo htmlspecialchars($_SERVER[" PHP_SELF "]);?>" autocomplete="off">
<div id="CountryNo" class="col-xs-3 form-group" style="font-size: 75%">
<select id="CountryNodd" name="CountryNodd" onChange="change_CountryNo()" class="form-control selectpicker" style="width:100%;">
<option>Country</option>
<?php
$res=mysqli_query($con, "SELECT * FROM countries ORDER BY Country_Descrip");
while($row=mysqli_fetch_array($res))
{
?>
<option value="<?php echo $row["CountryNo"]; ?>"><?php echo $row["Country_Descrip"]; ?></option>
<?php $CountryNodd = $_POST["CountryNo"]; ?>
<?php }
?>
</select>
</div>
<div id="StateID" class="col-xs-3 form-group" style="font-size: 75%">
<select id="StateIDdd" name="StateID" class="form-control selectpicker" style="width:100%;">
<option>Product</option>
</select>
</div>
<div id="CityID" class="col-xs-3 form-group" style="font-size: 75%">
<select id="CityIDdd" name="CityIDdd" class="form-control selectpicker" style="width:100%;">
<option>Brand</option>
</select>
</div>
<div class="form-group">
<img src="img\..." class="img-responsive" alt="Country-State-City Image" width="100%" height="auto">
<div class="col-lg-12 text-center">
<br>
<input type="submit" name="reset" id="reset" tabindex="3" class="form-control btn btn-register" value="Reset Country-State-City Selections" required>
</div>
</div>
<div class="form-group">
<div class="col-lg-12 text-center">
<br>
<input type="submit" name="Update My Country-State-City" id="update" tabindex="4" class="form-control btn btn-register" value="Update My Country-State-City" required>
</div>
</div>
</form>
<!-- end of form -->
</div>
<!-- end of row col-md-12 div -->
</div>
<!-- end of panel-body div -->
</div>
<!-- end of panel-heading div -->
</div>
<!-- end of panel-login div -->
</div>
<!-- end of col-md-6 col-md-offset-3 div -->
</div>
<!-- end of class row div -->
<!-- ajax.php -->
<!DOCTYPE HTML>
<html>
<head>
<title>ajax.php</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<?php
//THIS FILE PROCESSES THE JQUERY SELECT BASED ON COUNTRY INPUT AND
//THE STATE INPUT
// Turn off error reporting
error_reporting(0);
$con=mysqli_connect('localhost', 'root', '', 'contact_info');
mysqli_set_charset($con,"utf8");
if (!$con) {
die('Could not connect: ' . mysqli_error());
}
// Get the Country and State Values User Selects
$CountryNo=$_GET["CountryNo"];
$StateID=$_GET["StateID"];
//Check user selection for country and list states
if($CountryNo!="Country")
{
$query="SELECT State_ID, StateCountry_ID, State_Description FROM states WHERE StateCountry_ID=$CountryNo ORDER BY State_Description";
$result=mysqli_query($con, $query);
echo "<select id='StateIDdd' onchange='change_StateID()' selected>";
echo "<option>"; echo "State"; echo "</option>";
while($row=mysqli_fetch_array($result))
{
echo "<option value='$row[State_ID]'>"; echo $row["State_Description"]; echo "</option>";
}
echo "</select>";
}
//Check user selection for state and list cities
if($StateID!="State")
{
$query="SELECT CityID, City_Name, CountryNo, CityState_ID FROM cities WHERE CityState_ID=$StateID ORDER BY City_Name";
$result=mysqli_query($con, $query);
echo "<select>";
while($row=mysqli_fetch_array($result))
{
echo "<option value='$row[CityID]' selected>"; echo $row["City_Name"]; echo "</option>";
}
echo "</select>";
}
?>
<?php include("ajax2.php") //Go to post to MySQL processing
?>
</head>
</html>
<!-- ajax2.php -->
<!-- THIS FILE POSTS THE COUNTRY, STATE, CITY VALUES TO
MYSQLI AND UPDATES THE USER'S CONTACT LOCATION -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<?php include("includes/header.php") ?>
<?php include("includes/nav.php") ?>
<?
// Turn off error reporting
error_reporting(0);
$con=mysqli_connect('localhost', 'root', '', 'contact_info');
mysqli_set_charset($con,"utf8");
if (!$con) {
die('Could not connect: ' . mysqli_error());
}
?>
<?
// Ensure user is logged in to get values
// for ContactNo
php if (logged_in() === false) {
echo "Redirecting...";
redirect("../index.html");
}
//store country, state, city selection and update contact's location
$CountryNo = $_POST['CountryNodd'];
$StateID = $_POST['StateIDdd'];
$CityID = $_POST['CityIDdd'];
//Update MySQL
$sql = "UPDATE contact_location SET CountryNodd=$CountryNo, StateID=$StateID, CityID=$CityID";
$sql.= "WHERE ContactNo=$ContactNo"; //Contact info is from contact table accessed via function include in header.php
$res_update = mysqli_query($con,$sql);
if($res_update) {
echo "Location updated successfully";
}
else {
echo "Not working...";
}
?>
I've read related questions/responses, but none resolve my problem.
I am very new to jQuery & PHP programming with a MySQL backend.
Created a 3-level drop down (Country-State-City) form where users
can select country-state-city values, which will update
MySQL.
While I can GET and POST the Country variable, I have been
unsuccessful for State and City. I can see the correct value of
the State variable, but I do not see a value for the City variable.
Furthermore, I cannot POST either the State or City variables: I get an
"Index Undefined" error for the variables associated with each.
SOLVED: The POST execution was occurring before the JavaScript actions, and this is because PHP, server side, is executed before Java, client-side. I moved the MySQL update code into the PHP script at the point the City selection has occurred.
I will not provide the code because comments I received thus far suggest my documentation needs work. Certainly appreciate that feedback and will take steps to improve future posts. Thank you!

How to get via onclick and POST data on redirect with POST

I'm working using ajax,javascript, php and still new with this.
Here the scenario, I have a button with onclick function in my index.html page when I click that button I want it to redirect me to another my getdata.php page while posting and id. So when I've been redirected to my getdata.php page I just need to query using that id.
The button that trigger redirection are located at index.html <button class="btn btn-default print" name="print" data-username="{{"'.$row['msid'].'"}}" onclick="generatepdf()"><span class="icon-printer"></button>
The following codes I've been using right now. I hope I've got a lot of help right here.
index.html
<?php
session_start();
$conn = mysqli_connect("localhost","root","1234","a0");
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Cache-control" content="no-cache"> <!--The No-Cache-->
<!--Bootstrap 3.3.7 CSS-->
<link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!--Data Tables-->
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.13/css/dataTables.bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/responsive/2.1.1/css/responsive.bootstrap.min.css">
<!--Date Timepicker-->
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<!--Linear Icons-->
<link rel="stylesheet" href="https://cdn.linearicons.com/free/1.0.0/icon-font.min.css">
<!--Date Timepicker-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.7.14/js/bootstrap-datetimepicker.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.7.14/css/bootstrap-datetimepicker.min.css">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/simple-line-icons/2.4.1/css/simple-line-icons.min.css">
</head>
<body>
<nav class="navbar navbar-default">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">MENU</button>
<a class="navbar-brand" href="#"><span class="icon-bag"></span> SUPPLIER</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>
<div class="container-fluid">
<h2 >List of Machine</h2>
<div class="table-responsive">
<div align="right">
<button type="button" id="add_button" data-toggle="modal" data-target="#userModal" class="btn btn-success">New File <span class="fa fa-code-fork"></span></button>
</div>
<br>
<table id="user_data" class="table table table-bordered table-hover dt-responsive " width="100%">
<thead>
<tr>
<th width="5%">Image</th>
<th width="15%">Name</th>
<th width="10%">Date Added</th>
<th width="10%">Created By</th>
<th width="6%">Action</th>
</tr>
</thead>
</table>
</div>
</div>
</body>
</html>
<div id="userModal" class="modal fade">
<div class="modal-dialog">
<form method="post" id="user_form" enctype="multipart/form-data">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add New Business Type </h4>
</div>
<div class="modal-body">
<label>Business Name</label>
<input type="text" name="businessname" id="businessname" class="form-control" />
<br />
<label>Select Business Image</label>
<input type="file" name="businessimage" id="businessimage" />
<span id="user_uploaded_image"></span>
</div>
<div class="modal-footer">
<input type="hidden" name="user_id" id="user_id" />
<input type="hidden" name="operation" id="operation" />
<input type="submit" name="action" id="action" class="btn btn-success" value="Add" />
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</form>
</div>
</div>
<script type="text/javascript" language="javascript" >
$(document).ready(function(){
var dataTable = $('#user_data').DataTable({
"processing":true,
"serverSide":true,
"order":[],
"ajax":{
url:"fetch.php",
type:"POST"
},
});
$(document).on('click', '.update', function(){
var user_id = $(this).attr("id");
$.ajax({
url:"fetch_single.php",
method:"POST",
data:{user_id:user_id},
dataType:"json",
success:function(data)
{
$('#userModal').modal('show');
$('#businessname').val(data.businessname);
$('.modal-title').text("Update Business Type");
$('#user_id').val(user_id);
$('#user_uploaded_image').html(data.businessimage);
$('#action').val("Save Changes");
$('#operation').val("Edit");
}
})
});
$(document).on('click', '.delete', function(){
var user_id = $(this).attr("id");
if(confirm("Are you sure you want to delete this?"))
{
$.ajax({
url:"delete.php",
method:"POST",
data:{user_id:user_id},
success:function(data)
{
alert(data);
dataTable.ajax.reload();
}
});
}
else
{
return false;
}
});
function generatepdf() {
var name = $(this).data('msid');
if (name != undefined && name != null) {
window.location = 'reports/getdata.php';
$.ajax({
url:"reports/getdata.php",
method:"POST"
});
}
};​
});
</script>
<!--Data Table JS-->
<script type="text/javascript" src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.13/js/dataTables.bootstrap.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/responsive/2.1.1/js/dataTables.responsive.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/responsive/2.1.1/js/responsive.bootstrap.min.js"></script>
</body>
fetch.php
<?php
include('db.php');
include('function.php');
$query = '';
$output = array();
$query .= "SELECT * FROM machine_supplier ";
if(isset($_POST["search"]["value"]))
{
$query .= 'WHERE machine_description LIKE "%'.$_POST["search"]["value"].'%" ';
}
if(isset($_POST["order"]))
{
$query .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
}
else
{
$query .= 'ORDER BY msid DESC ';
}
if($_POST["length"] != -1)
{
$query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$statement = $connection->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$data = array();
$filtered_rows = $statement->rowCount();
foreach($result as $row)
{
$image = '';
if($row["image1"] != '')
{
$image = '<img src="machine_images/'.$row["image1"].'" class="img-thumbnail" width="50" height="35" />';
}
else
{
$image = '';
}
$sub_array = array();
$sub_array[] = $image;
$sub_array[] = $row["machine_description"];
$sub_array[] = $row["model_number"];
$sub_array[] = $row["supplier"];
$sub_array[] = '<select class="form-control">
<option selected disabled>YOUR ACTIONS</option>
<option name="update" id="'.$row["msid"].'" class="update">UPDATE</option>
<option name="delete" id="'.$row["msid"].'" class="delete">DELETE</option>
</select>
<button class="btn btn-default print" name="print" data-username="{{"'.$row['msid'].'"}}" onclick="generatepdf()"><span class="icon-printer"></button>
';
$data[] = $sub_array;
}
$output = array(
"draw" => intval($_POST["draw"]),
"recordsTotal" => $filtered_rows,
"recordsFiltered" => get_total_all_records(),
"data" => $data
);
echo json_encode($output);
?>
function.php
<?php
function upload_image()
{
if(isset($_FILES["image1"]))
{
$extension = explode('.', $_FILES['image1']['name']);
$new_name = rand() . '.' . $extension[1];
$destination = 'machine_images/' . $new_name;
move_uploaded_file($_FILES['image1']['tmp_name'], $destination);
return $new_name;
}
}
function get_image_name($user_id)
{
include('db.php');
$statement = $connection->prepare("SELECT image1 FROM machine_supplier WHERE msid = '$user_id'");
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row)
{
return $row["image1"];
}
}
function get_total_all_records()
{
include('db.php');
$statement = $connection->prepare("SELECT * FROM machine_supplier");
$statement->execute();
$result = $statement->fetchAll();
return $statement->rowCount();
}
?>
getdata.php
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "databasename";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_POST['print'])) {
$sql = "SELECT msid FROM machine_supplier WHERE";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
//data
}
} else {
echo "0 results";
}
} else{
//redirect back
}
?>
</body>
</html>
Easy way is not using JS or Jquery for your requirement. Just use HTML form and PHP only like following in your index.php.
<?php
//In you index.php
//.....................
//..........................
//your other codes
//......................
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
?>
<form method="post" action="getdata.php">
<input type="hidden" name="my_id" value="<?php echo $row['msid']; ?>" />
<input type="submit" value="REDIRECT AND POST MY ID" />
</form>
<?php
}
} else {
echo "0 results";
}
//.................
//.................
You just need to replace the button code with this form code and your ID will be posted and redirected to getdata.php page because of the form attribute action="getdata.php".
See the form method is post this means your form will be submitted using POST method. Now in your getdata.php file do following
<?php
$posted_id = $_POST['my_id'];
echo $posted_id;
//now get data from DB using this id
//get data from db where id = $posted_id
This is not full code for getdata.php but you will see at least your posted id(from index.php to getdata.php) using this code. There are lots to do like checking http method, error handling etc etc.

Refreshing a DIV dynamic

I am trying to load content into a div and auto updated in every 5 seconds.
I have searched the net and tried to use everything, But nothing works at all. I tried to load the output from pauseupdate2.php to the div pauseup
pause.php is in a folder <../user/pause.php>
<?php
include('../session/session.php');
include('../funktion/sitelocteam.php');
include('../funktion/pausecheck.php');
include('../funktion/pausetime.php');
//include('../funktion/pauseupdate.php');
include('../funktion/pauseupdate1.php');
include('../funktion/counter.php');
//include('../funktion/pauserules.php');
?>
<!DOCTYPE html>
<html>
<head>
<title>Pause Program</title>
<link href="../style/style.css" rel="stylesheet" type="text/css">
<link href="../style/menu.css" rel="stylesheet" type="text/css">
<link rel="import" href="../funktion/pauseupdate.php">
</head>
<body>
<div id="Holder">
<div id="Header"></div>
<div id="NavBar"><nav>
<ul>
<li>Pause</li>
<li>Profil
<ul>
<li>Min Pauseoversigt </li>
</ul>
</li>
<li>FAQ</li>
<li>Logout</li>
</ul>
</nav>
</div>
<div id="PageHeading">
<!-- <h3> Bruger ID: <?php echo $userid; ?></h3>-->
<h3> Intialer: <?php echo $_SESSION['login_user']; ?> </h3>
<h3> Team: <?php echo $teamname ?></h3>
<h3> Lokation: <?php echo $sitename ?></h3>
</div>
<div id="pausev">
<?php
if ($pausetime->num_rows > 0) {
// output data of each row
while($row = $pausetime->fetch_assoc()) {
echo "Du har holdt pause siden: " . $row["time"]. "<br>";
}
}
?>
<div id="pauseup"></div>
<script src="../js/jquery-1.11.3.min.js"></script>
<script src="../js/pause.js"></script>
</div>
<div id="Pause">
<!-- <?php
echo $errors;
?> <br> <br>-->
<form action="../funktion/pauserules.php">
<input type="submit" value="PAUSE!"<?php if ($pausetjek->num_rows > 0 ){?> disabled <?php }?> >
</form>
<form action="../funktion/pausestop.php">
<input type="submit" value="STOP!" <?php if ($pausetjek->num_rows === 0){?> disabled <?php }?> >
</form>
</div>
<div id="Footer"></div>
</div>
</body>
</html>
The pause.js looks like this:
$(document).ready(function()
{
// Load the content of "path/to/script.php" into an element with ID "#container".
$('#pauseup').load('../funktion/pauseupdate2.php');
// Execute every 5 seconds
window.setInterval(refreshData, 5000);
}
);
And last but least pauseupdate2.php looks like:
<?php
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "pause";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "select user.username from pause LEFT OUTER JOIN user on pause.userid=user.id where pause.type=0";
$pauseupdate = $conn->query($sql);
if ($pauseupdate->num_rows > 0) {
// output data of each row
while($row = $pauseupdate->fetch_assoc()) {
echo "Hvem er til pause: " . $row["username"]. "<br>";
// print '<table>
// <tr>
// <td>'.$row['username'].'</td>
// </tr>
// </table>';
}
} else {
echo "Ingen er til pause!";
}
$conn->close();
echo 'booo';
?>
What may be wrong with my code?
I know the most of it may be bad coded, and I am new to PHP and Jquery.
Thanks in advance
You are calling a function "refreshData" but it is not defined.
Define the function, call it the first time from the $(document.ready() method, and add setInterval at the same time:
function refreshData(){
$('#pauseup').load('../funktion/pauseupdate2.php');
}
$(document).ready(function()
{
// Execute every 5 seconds
window.setInterval(refreshData, 5000);
refreshData();
});
I think the problem could come from this refreshData function that does not seem to exist...
Try with this code (very close to yours)
<body>
<h1>Load refresh...</h1>
<div class="content">
content that will be overwritten...
</div>
<script type="text/javascript">
setInterval(function(){
$('.content').load('my_url_to_reload_every_3_seconds.php');
}, 5000);
</script>

Ajax- fill multiple textboxes for php

I have a html page with a drop down menu, The menu works and onchange calls a function popBox() that too works. Within the function i am using ajax to post the value of the drop down menu into php where it selects form the db. I wish to fill the textboxes in the form "DetailsForm" with the information selected. I currently fill no text boxes and the alert (msg) displays the whole html side of the page in and alert box. Could somebody please help me with my problem. I have tried multiple different variation of ajax and jquery to perform this and after 15hrs on the same function i am starting to get slight frustrated to say the least. Thanks in advance for any help, i do appreciate it.
Here is my code:
HTML
<head>
<link href="../UserTemplate.css" rel="stylesheet" type="text/css"/>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- TemplateBeginEditable name="doctitle" -->
<title>Tours</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"> </script>
<script type="text/javascript">
function popBox(str)
{
$.ajax({
type: "PopulateBoxes.php",
data: { dat: str}
}).done(function( msg ) { //you can also use success
alert( "Data Saved: " + msg );
});
//document.getElementById("txt_Duration").value = <?php Print($Duration); ?>;
//document.getElementById("txt_Vessel_Name").value = <?php Print($Vessel); ?>;
//document.getElementById("txt_Location").value = <?php Print($Location); ?>;
//document.getElementById("txt_Available").value = <?php Print($Available); ?>;
//document.getElementById("txt_Price").value = <?php Print($Price); ?>;
}
</script>
</head>
<body>
<div id="MainDiv">
<div id="Header">
<div id="Logo"><img src="../Scotia Sea Life Logo.png" width="150px" height="110px" alt="Company Logo"/></div>
<div id="NavBar"><ul>
Home Tours About Donate Account
</ul>
</div>
<div id="Title">Tours</div>
</div>
<div id="Content">
<div id="Search">
<div id="SearchDiv">
<form id="SelectTourForm" style="margin:5px;">
<table border="0" align="center" width="100%">
<tr>
<td>
<label style="color:#FFF; font:Georgia, 'Times New Roman', Times, serif; font-size:20px; margin-left:10px; margin-top:25px">Select Tours Details</label></td>
</tr>
<tr>
<td><select name="lst_MonthDrop" style="background-color:#FF9933; color:#FFF; border:none; margin-top:10px; margin- left:10px;" onchange="popBox(this.value);">
<option>Please Select</option>
<?php
include 'populatedrodown.php';
foreach ( $results as $option ) : ?>
<option value="<?php echo $option- >Date; ?>"><?php echo $option->Date; ?></option>
<?php endforeach; ?>
</select>
<input type="submit" name="btn_TourSearch" id="btn_TourSearch" value="Search" style="background:#009300; border-radius:5px; border-color:#009300; color:#FFF;margin-left:5px;" /></td>
</tr>
<tr>
<td></td>
</tr>
</table>
<p> </p>
</form>
</div>
</div>
<div id="DetailsDiv">
<div id="DetailsContent">
<form id="DetailsForm" >
<table border="0" align="center" width="100%">
<tr><td><label style="color:#FFF; font-size:14px;">Tour ID</label> <input type="text" id="Tour_ID" /> </td></tr>
<tr><td><label>Duration</label> <input type="text" id="txt_Duration" /> </td></tr>
<tr><td><label>Vessel Name</label> <input type="text" id="txt_Vessel_Name"/> </td></tr>
<tr><td><label>Location</label> <input type="text" id="txt_Location" /> </td></tr>
<tr><td><label>Date</label> <input type="text" id="txt_Date" /> </td></tr>
<tr><td><label>Available</label> <input type="text" id="txt_Available" /> </td></tr>
<tr><td><label>Price</label> <input type="text" id="txt_Price" /> </td></tr>
</table>
</form>
</div>
</div>
</div>
<div id="Footer">
<div id="FooterLinks"></div>
</div>
</div>
</body>
</html>
PHP
<?php
$q = $_POST['dat'];
$mysql_db_hostname = "localhost";
$mysql_db_user = "root";
$mysql_db_password = "pwd";
$mysql_db_database = "db";
$con = mysql_connect($mysql_db_hostname, $mysql_db_user, $mysql_db_password) or die("Could not connect database");
mysql_select_db($mysql_db_database, $con) or die("Could not select database");
$sql="SELECT * FROM Tour WHERE Date = '".$q."'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
$Duration = $row['Duration'] ;
$Vessel = $row['Vessel_Name'] ;
$Location = $row['Location'] ;
$Available = $row['Available'];
$Price = $row['Price'];
}
mysqli_close($con);
?>
Try to modify you JS code similar to this:
function popBox(selectValue) {
$.ajax({
type: 'POST',
url: "PopulateBoxes.php",
data: { dat: selectedValue },
success: function(serverResponse) {
// after success request server should return response with data
// that will be passed to this callback function as parameter
// and you can use it to fill text boxes:
$('#txt_Duration').val(serverResponse.duration);
}
});
}
Also you should modify your PHP code to return data in JSON:
// At the end you should return selected array. For example:
echo json_encode($dataArray); exit;
As you are using $_POST in your PHP code, you would need to edit the ajax call script.
Type is either GET or POST and page address comes in to the url attribute.
$.ajax({
type: 'POST',
url: "PopulateBoxes.php",
data: { dat: str}
}).done(function( msg ) { //you can also use success
alert( "Data Saved: " + msg );
});
}

Categories

Resources