Refreshing a DIV dynamic - javascript

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>

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>

prevent refresh on submit and clear input after submit

I want to build a website that can make people post things and comments on it
now I have some problems
I hope that I could submit the comment without refreshing the page (I found a way to solve this problem but the input won't be cleared)
I already search a lot of information about preventing refresh page on submit but there is no one works for me
and I hope that someone can help me with another problem
I want to make the website show the comment immediately after posting it (without refreshing the page)
directly edit my code and paste on here will be appreciated
below is my index.php
<?php
session_start();
require_once 'db.php';
require_once 'new_tdb.php';
//$datas = get_publish_article();
if(isset($_COOKIE["mcsh"])){
}else{
header("Location: ../mcsh/login/index.php");
exit();
}
?>
<html>
<head>
<title>
website
</title>
<link rel="shortcut icon" href="icon.png" type="image/x-icon" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
<?php include 'menu.css' ?>
</style>
</head>
<body>
<?php include 'menu.php' ?>
<center>
<font class="corn-blue">
</font>
</center>
<p> </p>
<?php
$bij = "SELECT * FROM `post` WHERE `comment` != 1 order by id DESC";
$result = mysqli_query($conn, $bij);
$rows = mysqli_num_rows($result);
while($row = mysqli_fetch_array($result)){
$post_id = $row['id'];
$ins = $row['ins'];
$s_uid = $row['s_uid'];
$p_id = $row['id'];
//$selc = "SELECT * FROM `post` WHERE `post_id` = $p_id";
?>
<center>
<table>
<tr>
<th>
Poster: <?php echo $s_uid;?>
</th>
</tr>
<tr>
<td>
<?php echo $ins;?>
</td>
</tr>
<tr>
<td>
<details>
<summary>Comment</summary>
<form id="worker" action="comment.php" method="post" target="the_iframe">
<input type="hidden" name="post_id" value="<?php echo $p_id; ?>">
<p><input type="text" name="comment" placeholder="Comment......"> <input type="submit" hidefocus="true" name="submit"></p>
</form>
<iframe id="is_iframe" name="the_iframe" style="display: none;"></iframe>
<?php
$sel = "SELECT * FROM `post` WHERE `post_id` = $post_id order by id DESC";
$result2 = mysqli_query($conn, $sel);
$rows2 = mysqli_num_rows($result2);
while($row2 = mysqli_fetch_array($result2)){
$ins2 = $row2['ins'];
$poster2 = $row2['s_uid'];
?>
<p><?php echo $poster2 . ': ' . $ins2; ?></p>
<?php } ?>
</details>
</td>
</tr>
</table>
</center>
<h1>
-
</h1>
<?php
}
?>
<?php if (empty($row['file'])){
}else{
echo('<img src="image/'); echo $row['file']; echo('"width="100%" height="auto">');
}
?>
</body>
</html>
As #Barmar said you want to use AJAX for Asynchronous actions in your website. Submit event must refresh the page to resend the new form data.
PHP is synchrony, what means if you want to do something with synchronous codes you will need to refresh the whole page.
Lear Further : Javascript documentation of Ajax by mozila here

append a div that includes php into a div

I have a div with an ID of intro, i want to append a div containing php that will give me data from my database when i clicked a button. i have successfully append <li> successfully but when I want to append a div containing php it wont append.
<div class="container" id="article">
<button id="addArticle()" onClick="addArticle()">+</button>
<div class="section" id="intro">
<?php
require_once("dbconfig.php");
$query = mysqli_query($koneksi, "SELECT * FROM content WHERE id=1");
while($row = mysqli_fetch_array($query))
{ ?>
<?php echo $row['content']; ?>
<?php
}
?>
</div>
<div class="section" id="usage">
<?php
require_once("dbconfig.php");
$query = mysqli_query($koneksi, "SELECT * FROM content WHERE id=2");
while($row = mysqli_fetch_array($query))
{ ?>
<?php echo $row['content']; ?>
<?php
}
?>
</div>
</div>
Code that I want to append when I click the + button:
<div class="section" id="intro">
<?php
require_once("dbconfig.php");
$query = mysqli_query($koneksi, "SELECT * FROM content WHERE id=8");
while($row = mysqli_fetch_array($query))
{ ?>
<?php echo $row['content']; ?>
<?php
}
?>
</div>
Javascript:
function addArticle(){
$('#article').append('<li>tes2</li>');
}
PHP has already done in server side before the page send to you.
In your case, you may try to use AJAX.
I did a simple example for you, but you need to make it fit to your solution.
view.php
<html>
<head>
<script>
function showContent()
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
document.getElementById("paragraph").innerHTML = this.responseText;
}
}
xmlhttp.open("GET","content.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
Name : <span id="paragraph"></span>
<br /><br />
<button onclick="showContent()">Show me</button>
</body>
</html>
content.php
<?php
echo "milan";
?>
Hope it help ;)

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.

onClick with Bootstrap, JavaScript and MySQL

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

Categories

Resources