onClick with Bootstrap, JavaScript and MySQL - javascript

What I'm trying to do is, SELECT * customers from a database, insert them into a dropdown menu, and when I choose a customer from that particular dropdown menu, his other data is outputted, like mobile number and email.
This is my code:
PS. Sorry about all the "echo", I had it crash on me a couple of times, I'm new to PHP
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/css/bootstrap-select.min.css" />
</head>
<body>
<?php $servername="localhost" ; $username="admin_default" ; $password="_" ; $dbname="admin_default" ; // Create connection $conn=n ew mysqli($servername, $username, $password, $dbname); ?>
<div class="container">
<div class="row">
<h2>Choose a customer</h2>
<hr/>
</div>
<div class="row-fluid">
<select class="selectpicker" data-show-subtext="true" data-live-search="true">
<?php // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } echo "Connected successfully
<br>"; $sql = "SELECT * FROM customers"; $result = $conn->query($sql); if ($result->num_rows > 0) { // output data of each row while($row = $result->fetch_assoc()) { echo "
<option onclick='loadData(";
echo $row[' id '];
echo ");'>"; echo $row['company_name']; echo "</option>"; } } else { echo '
<option>No customers found</option>'; } $conn->close(); ?>
</select>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/js/bootstrap-select.min.js"></script>
<script type="text/javascript">
function loadData(d) {
console.log(d);
}
</script>
</body>
</html>

Try this
$query=Select * from customers
...
while($row=mysqli_fetch_array($res)){
echo "<option value="'.$row['data_id'].'">".$row['data']."</option>";
}
And your js
dropdown.on(change, function(){
Get the value of the dropdown and use it for your query to display data.
});

Related

Why a request to the database is reflected through the form, but not sent through AJAX

JQuery connected, AJAX probably works correctly, because when I change select in the console the values are correct. But the query to the database doesn't change. Checking var_dump($_POST['filter']) shows that there value from previous request.
If I wrap select in a form and send it via POST using submit button, the requests are sent.
Where can there be an error here?
And how to add a condition, so that when selecting "All" the query will just be to all items "SELECT * FROM orders, without the condition "WHERE?
<script>
$('#filter').change(function() {
$.ajax({
method: "POST",
url: "thispage.php",
data: {
filter: $("#filter").val()
},
success: function(response) {
console.log($("#filter").val())
}
});
});
</script>
<?php
require_once __DIR__ . "/database/database.php";
$item1 = $_POST['item1'];
$worker_name = $_POST['worker_name'];
$worker_company = $_POST['worker_company'];
$errors = [];
if (empty($item1)) {
$errors['item1'] = true;
}
if (empty($errors)) {
$sql = "INSERT INTO `orders`(`order_dish1`, `order_name_worker`, `order_company`) VALUES (:order1, :order_name_worker, :worker_company)";
$params = [
"order1" => $item1,
"order_name_worker" => $worker_name,
"worker_company" => $worker_company
];
$dbh->prepare($sql)->execute($params);
}
$order_dishes1 = [];
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Document</title>
</head>
<body>
<select type="text" name="filter" id="filter">
<option value="*">All</option>
<?php
$sql = "SELECT * FROM `companies`";
$rows = $dbh->query($sql);
foreach ($rows as $row) {
?>
<option value="<?php echo $row['name'] ?>">
<?php echo $row['name'] ?>
</option>
<?php } ?>
</select>
// In this form it works
<form action="thispage.php" method="POST">
<select type="text" name="filter" id="filter">
<option value="*">All</option>
<?php
$sql = "SELECT * FROM `companies`";
$rows = $dbh->query($sql);
foreach ($rows as $row) {
?>
<option value="<?php echo $row['name'] ?>">
<?php echo $row['name'] ?>
</option>
<?php } ?>
</select>
<button type="submit">submit</button>
</form>
<div class="orders__wrapper" id="result">
<?php
$company = $_POST['filter'];
var_dump($_POST['filter']);
$sql = "SELECT * FROM `orders` WHERE `order_company` = '$company'";
$rows = $dbh->query($sql);
foreach ($rows as $row) {
?>
<div class="order-items">
<div class="order-items__header">
<div class="order-items__wrapper">
<div class="order-items__number">
Order №: <?php echo $row['order_id'] ?> </div>
</div>
<div class="order-items__wrapper">
<div class="order-items__name">
<?php echo $row['order_name_worker'] ?> </div>
<div class="order-items__company">
Company:
<span>
<?php echo $row['order_company'] ?>
</span>
</div>
</div>
</div>
<div class="order-items__orders">
<div class="orders-item orders-item-1">
Order №1:
<span class="order1">
<?php echo $row['order_dish1'] ?>
</span>
</div>
</div>
</div>
<?php
$order_dishes1[] = $row['order_dish1'];
}
$content = ob_get_contents();
ob_end_clean();
?>
<div class="result__all" id="result__all">
<div class="result__all-company">
<?php echo $row['order_company'] ?>
</div><br>
<div class="result__all__wrapper">
<div class="result__all-view">
<div class="result__all-title">
Soups:
</div>
<?php
$count_dishes1 = array_count_values($order_dishes1);
foreach ($count_dishes1 as $key => $val) echo '<div class="result__all-item">' . $key . ' - ' . $val . ' шт.,</div>';
?>
</div><br>
</div>
</div>
<?= $content ?>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
</body>
</html>

Button has to be pressed to activate php code? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
So the idea of this website is that when you press the button it deletes the corresponding row from the database. However, the issue with my code is that after the first press the button fills the id variable and then executes the php on the next press. How can I avoid this and get he php to fit and execute the php on the first press of the button?
Included is the HTML page with the php embedded:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<title>Untitled Document</title>
<style>
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
</style>
</head>
<body>
<div class="container-fluid">
<h2 style"text-align:center";>Please enter the item you want to add to the list below </h2>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
$sql = "CREATE DATABASE myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "CREATE TABLE freezerinventory (
id INT AUTO_INCREMENT PRIMARY KEY,
item VARCHAR(30) NOT NULL,
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)";
if(isset($_POST['itemx']))
{
$itemvar = $_POST["itemx"];
$sql = "INSERT INTO freezerinventory (item)
VALUES ('$itemvar')";
$add = mysqli_query($conn, $sql);
}
else {
$sql = "";
}
mysqli_close($conn);
?>
<form action="<?=$_SERVER['PHP_SELF'];?>" class="needs-validation" novalidate method="post">
<div class="form-group">
<label for="uname"></label>
<input type="text" class="form-control" id="itemx" placeholder="Enter an item for the freezer here" name="itemx" required>
<div class="valid-feedback">Valid.</div>
<div class="invalid-feedback">Please fill out this field.</div>
</div>
<button id = "SubmitButton" name = "SubmitButton" type="button submit" class="btn btn-primary">Add to list</button>
</form>
</div>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
$aVar = mysqli_connect('localhost','root','','myDB');
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM freezerinventory";
$result = mysqli_query($aVar, $sql);
echo "<table><tr>
<th>Item name</th>
<th>Date added</th>
<th>remove</th>
</tr> ";
while($row = mysqli_fetch_array($result)) {
echo " <tr><td>" . $row['item'] . "</td><td>" . $row['reg_date'] . "</td><td><form action='
' method='POST'>
<div class= 'input-group' > <div class='input-group-append'>
<button class='btn btn-danger' onclick='deleteitem()' id = 'delete' type='submit'>Remove</button>
<input type='hidden' name='id' value=".$row['id']." />
</div></div>
</form></td></tr>";
}
echo "</table>";
?>
<script>
function deleteitem (e) {
e.preventDefault();
<?php
$id = $_POST['id'];
$delete = "DELETE FROM freezerinventory WHERE id=$id";
$del = mysqli_query($conn, $delete);
?>
}
else {
}
</script>
<script>
function myFunction() {
confirm("I am an alert box!");
}
</script>
<script>
(function() {
'use strict';
window.addEventListener('load', function() {
// Get the forms we want to add validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
</script>
</body>
</html>
You can create a separate processing script and submit a form to the URL path 'onClick' of a button. You cannot directly call PHP function with JS code.
PHP is a language that runs only on server-side.
It is different to javascript that runs on client-side (on the browser).
If you may notice, you will never see PHP code on other websites, because (if the website uses PHP) it is processed on the server side and the return is HTML+CSS only.
Nowaday we would not create a page like this.
We would create what we call API using PHP. We would use REST-API strategy.
Let's say we would host this API on this address www.mywebsite.com/myapi/myfreezerendoint.php
And we would use JS to request or post to this endpoint with simple javascript function called fetch("www.mywebsite.com/myapi/myfreezerendoint.php", { ... }).
I found this interesting tutorial about PHP API with MySQL as database: https://webdamn.com/create-simple-rest-api-with-php-mysql/
I hope you enjoy! Keep it up
I've corrected and beautified all of the code, minimized it and this should now be it:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
$sql = "CREATE DATABASE myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "CREATE TABLE freezerinventory (
id INT AUTO_INCREMENT PRIMARY KEY,
item VARCHAR(30) NOT NULL,
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP)";
if(isset($_POST['itemx'])) {
$itemvar = $_POST["itemx"];
$stmt = $conn->prepare("INSERT INTO freezerinventory (item) VALUES ('?')");
$stmt->bind_param("s", $itemvar);
$stmt->execute();
} else {
//the 'itemx' post parameter isn't set, make an alert or something
}
mysqli_close($conn);
?>
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<title>Untitled Document</title>
<style>
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
</style>
</head>
<body>
<div class="container-fluid">
<h2 style"text-align:center";>Please enter the item you want to add to the list below </h2>
<form action="<?php echo $_SERVER["PHP_SELF"];?>" class="needs-validation" novalidate method="post">
<div class="form-group">
<label for="uname"></label>
<input type="text" class="form-control" id="itemx" placeholder="Enter an item for the freezer here" name="itemx" required>
<div class="valid-feedback">Valid.</div>
<div class="invalid-feedback">Please fill out this field.</div>
</div>
<button id = "SubmitButton" name = "SubmitButton" type="button submit" class="btn btn-primary">Add to list</button>
</form>
</div>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
$aVar = mysqli_connect('localhost','root','','myDB');
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['id'])) {
$delete = $con->prepare("DELETE FROM freezerinventory WHERE id= ?");
$delete->bind_param("s", $_POST['id']);
$delete->execute();
}
$sql = "SELECT * FROM freezerinventory";
$result = mysqli_query($aVar, $sql);
echo "<table><tr>
<th>Item name</th>
<th>Date added</th>
<th>remove</th>
</tr> ";
while($row = mysqli_fetch_array($result)) {
echo " <tr><td>" . $row['item'] . "</td><td>" . $row['reg_date'] . "</td><td><form action='' method='POST'>
<div class= 'input-group' > <div class='input-group-append'>
<button class='btn btn-danger' onclick='deleteitem(".$row['id'].")' id='delete'>Remove</button>
<input type='hidden' name='id'/>
</div></div>
</form></td></tr>";
}
echo "</table>";
?>
<script>
function deleteitem (id_data) {
$.post('<?php echo $_SERVER["PHP_SELF"];?>', {id: id_data}, function(data) {
console.log(data); //callback data
});
}
function myFunction() {
confirm("I am an alert box!");
}
(function() {
'use strict';
window.addEventListener('load', function() {
// Get the forms we want to add validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
</script>
</body>
</html>
It might still need some fixes and I left some unused html elements in there but in theory this should work. It makes use of ajax to send the data to php. You don't have to use ajax but this should in theory solve your problem. If you run into any issues just comment under my answer.
NOTE: Just to clarify, I didn't try this therefore there might be some errors in there.

How do i stop a page from scrolling to the top when button clicked in php?

How do I stop a page from scrolling to the top when button Add to cart is clicked?
since i have a lot of products showing up from database to my page, this refreshing the "index.php" to the top is make me frustrated.
Btw i'm following this tutorial http://www.onlinetuting.com/e-commerce-website-in-php-mysqli-video-tutorials/
PS: i'm a beginner so just help me with an example (the line where to put the code is important for me).
//index.php (short code only)
<!doctype html>
<?php
include ("functions/functions.php");
?>
<html>
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="styles/style.css" type="text/css" media="all" />
<script src="js/jquery-3.0.0.min.js"></script>
</head>
<body>
<div class="container">
<div class="header"></div>
<div class="navigation">
<div> <?php getCats(); ?> <?php getBrands(); ?> </div>
<div> </div>
<div id="shopping_cart"> Go to Cart <?php total_items(); ?> <?php total_price(); ?> </div>
</div>
<div id="content">
<?php cart(); ?>
<div id="products"> <?php getPro(); ?> <?php getCatPro(); ?> <?php getBrandPro(); ?> </div>
</div>
<div id="footer"></div>
</div> <!--END OF "container" -->
</body>
</html>
//function.php
<?php
$con = mysqli_connect("localhost","root","","learning-php");
if (mysqli_connect_errno())
{
echo "The connection was not established: " . mysqli_connect_error();
}
//Creating the shopping cart
function cart(){
if(isset($_GET['add_cart'])){
global $con;
$ip = getIp();
$pro_id = $_GET['add_cart'];
$check_pro = "select * from cart where ip_add='$ip' AND p_id='$pro_id'";
$run_check = mysqli_query($con, $check_pro);
if(mysqli_num_rows($run_check)>0){
}
else {
$insert_pro = "insert into cart (p_id,ip_add) values ('$pro_id','$ip')";
$run_pro = mysqli_query($con, $insert_pro);
echo "<script>window.open('index.php','_self')</script>";
}
}
}
//Getting the total added items
function total_items(){
if(isset($_GET['add_cart'])){
global $con;
$ip = getIp();
$get_items = "select * from cart where ip_add='$ip'";
$run_items = mysqli_query($con, $get_items);
$count_items = mysqli_num_rows($run_items);
}
else {
global $con;
$ip = getIp();
$get_items = "select * from cart where ip_add='$ip'";
$run_items = mysqli_query($con, $get_items);
$count_items = mysqli_num_rows($run_items);
}
echo $count_items;
}
//Getting the total price of the items in the cart
function total_price(){
$total = 0;
global $con;
$ip = getIp();
$sel_price = "select * from cart where ip_add='$ip'";
$run_price = mysqli_query($con, $sel_price);
while($p_price=mysqli_fetch_array($run_price)){
$pro_id = $p_price ['p_id'];
$pro_price = "select * from products where product_id='$pro_id'";
$run_pro_price = mysqli_query($con,$pro_price);
while($pp_price = mysqli_fetch_array($run_pro_price)){
$product_price = array($pp_price['product_price']);
$values = array_sum($product_price);
$total +=$values;
}
}
echo "$ " . $total;
}
//Getting the categories
function getCats(){
global $con;
$get_cats = "select * from categories";
$run_cats = mysqli_query($con, $get_cats);
while ($row_cats=mysqli_fetch_array($run_cats)){
$cat_id = $row_cats['cat_id'];
$cat_title = $row_cats['cat_title'];
echo "<li><a href='index.php?cat=$cat_id'>$cat_title</a></li>";
}
}
//Getting the brands
function getBrands(){
global $con;
$get_brands = "select * from brands";
$run_brands = mysqli_query($con, $get_brands);
while ($row_brands=mysqli_fetch_array($run_brands)){
$brand_id = $row_brands['brand_id'];
$brand_title = $row_brands['brand_title'];
echo "<li><a href='index.php?brand=$brand_id'>$brand_title</a></li>";
}
}
//Showing the products
function getPro(){
if(!isset($_GET['cat'])){
if(!isset($_GET['brand'])){
global $con;
$get_pro = "select * from products";
$run_pro = mysqli_query($con, $get_pro);
while ($row_pro=mysqli_fetch_array($run_pro)){
$pro_id = $row_pro['product_id'];
$pro_cat = $row_pro['product_cat'];
$pro_brand = $row_pro['product_brand'];
$pro_title = $row_pro['product_title'];
$pro_price = $row_pro['product_price'];
$pro_image = $row_pro['product_image'];
echo "
<div id='products'>
<h3>$pro_title</h3>
<img src='admin_area/product_images/$pro_image' width='135' height='100'/>
<div class='details'>
<p><div id='prc'>Price:</br><b>$. $pro_price </b></div></p>
<p><div id='a2c'><a href='?add_cart=$pro_id'><button style='float:left;'>Add to Cart</button></a></div></p>
<p><div id='fDtl'><a href='full_details.php?pro_id=$pro_id' style='float:left;'>Full Details</a></div></p>
</div>
</div>
";
}
}
}
}
//Showing the products by categories
function getCatPro(){bla,bla,bla}
//Showing the products by brands
function getBrandPro(){bla,bla,bla}
?>
//what i mean is this line (function.php)
div#a2c
//effected to this line (index.php)
div#products
See What i mean
Override default form submit by calling preventDefault and call the action as a ajax call. Make sure that the script is loaded like put it in head section
refer this example:
var element = document.querySelector("form");
element.addEventListener("submit", function(event) {
event.preventDefault();
// actual logic, e.g. validate the form
alert("Form submission cancelled.");
});
<form>
<button type="submit">Submit</button>
</form>
Here is a complete example from http://www.tutorialspoint.com/jquery/events-preventdefault.htm:
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src = "http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("a").click(function(event){
event.preventDefault();
alert( "Default behavior is disabled!" );
});
});
</script>
</head>
<body>
<span>Click the following link and it won't work:</span>
GOOGLE Inc.
</body>
</html>

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>

Retain Data Recieved from Database on HTML form

<?php
include_once 'database_connect.php';
$conn = new dbconnection();
$dbcon = $conn->connect();
if (!$dbcon) {
die("Fail".mysqli_error($dbcon));
}
?>
<html>
<head>
<title></title>
<script type="text/javascript"></script>
</head>
<body>
<form name="frm" method="post" action='<?php echo $_SERVER['PHP_SELF']; ?>'>
<table width="50%" border="1" cellpadding="3" cellspacing="3" align="center">
<?php
$value1 = array();
$select_query = "SELECT Distinct branch FROM subjects";
$result = mysqli_query($dbcon, $select_query);
if (!$result) {
die("Fail".mysqli_error($dbcon));
}
while ($row = mysqli_fetch_array($result)) {
$value1[] = $row['branch'];
}
?>
<tr>
<td>Branch
<td><select name="branch" id="branch" onchange="document.frm.submit();">
<option>Select Branch</option>
<?php
foreach ($value1 as $gets)
echo "<option value={$gets}>{$gets}</option>";
?>
</select>
<?php
$value2 = array();
if (isset($_POST['branch'])) {
$branch = $_POST['branch'];
$getsub_query = "SELECT sub_code FROM subjects where branch='$branch'";
$result2 = mysqli_query($dbcon, $getsub_query);
if (!$result2) {
die("Fail\n".mysqli_error($dbcon));
}
while ($row1 = mysqli_fetch_array($result2)) {
$value2[] = $row1['sub_code'];
}
}
?>
<tr>
<td>Subject Code
<td><select name="subcode" id="subcode">
<option>Subject Code</option>
<?php
foreach ($value2 as $gets)
echo "<option value={$gets}>{$gets}</option>";
?>
</select>
This code gets the first drop down list branch from data base. When we select value from it, second drop down list get filled from database . but problem is when i select option in first drop down list, the selected option does not remain their in first drop down list . but second drop down list fills correctly. i want that option i have selected should remain selected. Like its state should be changed. I think first drop down list gets filled again on form load.
You have to mention in your html that the option is indeed selected.
Try replacing
echo "<option value={$gets}>{$gets}</option>";
By
$selected = '';
if (isset($_POST['branch'] && $gets==$_POST['branch']) {
$selected = ' selected="selected"';
}
echo "<option value={$gets}".$selected.">{$gets}</option>";

Categories

Resources