Ajax and SQL population of a dropdown - php

This seems to be the pain of my life I have now spent hours on this and none of the researched solutions seem to fix it. My code is supposed to populate a dropdown from a database called "notes" the field that is populated from is supposed is "name" and then the program is supposed to select all of the records with the name as the same selected. Except it does not seem to populate the list. I don't think that it's a database connection error as when all patients is selected all the records show up.
Here's my code:
<?php
// php select option value from database
$hostname = "localhost";
$username = "root";
$password = "";
$databaseName = "CareM_database";
// connect to mysql database
//load_data_select.php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$connect = mysqli_connect($hostname, $username, $password, $databaseName);
function fill_name($connect)
{
$output = '';
$sql = "SELECT name, id FROM name";
$result = mysqli_query($connect, $sql);
while($row = mysqli_fetch_array($result))
{
$output .= '<option value="'.$row["id"].'">'.$row["name"].'</option>';
}
return $output;
}
function fill_patients($connect)
{
$output = '';
$sql = "SELECT * FROM notes";
$result = mysqli_query($connect, $sql);
while($row = mysqli_fetch_array($result))
{
$output .= '<div class="col-md-3">';
$output .= '<div style="border:1px solid #ccc; padding:20px; margin-bottom:20px;">'.$row["details"].'';
$output .= '</div>';
$output .= '</div>';
}
return $output;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Patient Notes View</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
<br /><br />
<div class="container">
<h3>
<select name="name" id="name">
<option value="">Show All Patients</option>
<?php echo fill_patients($connect); ?>
</select>
<br /><br />
<div class="row" id="show_patients">
<?php echo fill_patients($connect);?>
</div>
</h3>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('#name').change(function(){
var name_id = $(this).val();
$.ajax({
url:"load_data.php",
method:"POST",
data:{id:id},
success:function(data){
$('#show_name').html(data);
}
});
});
});
</script>

You are not calling fill_name function in your select, but calling fill_patients instead, And I don't see any element with the id of #show_name in your html.
<?php
// php select option value from database
$hostname = "localhost";
$username = "root";
$password = "";
$databaseName = "CareM_database";
// connect to mysql database
//load_data_select.php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$connect = mysqli_connect($hostname, $username, $password, $databaseName);
function fill_name($connect)
{
$output = '';
$sql = "SELECT name, id FROM name";
$result = mysqli_query($connect, $sql);
while($row = mysqli_fetch_array($result))
{
$output .= '<option value="'.$row["id"].'">'.$row["name"].'</option>';
}
return $output;
}
function fill_patients($connect)
{
$output = '';
$sql = "SELECT * FROM notes";
$result = mysqli_query($connect, $sql);
while($row = mysqli_fetch_array($result))
{
$output .= '<div class="col-md-3">';
$output .= '<div style="border:1px solid #ccc; padding:20px; margin-bottom:20px;">'.$row["details"].'';
$output .= '</div>';
$output .= '</div>';
}
return $output;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Patient Notes View</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
</script>
</head>
<body>
<br /><br />
<div class="container">
<h3>
<select name="name" id="name">
<option value="">Show All Patients</option>
<!-- <?php echo fill_patients($connect); ?> -->
<!-- call fill_name function instead of the above function -->
<?php echo fill_name($connect); ?>
</select>
<br /><br />
<div class="row" id="show_patients">
<?php echo fill_patients($connect);?>
</div>
</h3>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script>
$(document).ready(function(){
$('#name').change(function(){
var name_id = $(this).val();
$.ajax({
url:"load_data.php",
method:"POST",
data:{id: name_id},
success:function(data){
$('#show_name').html(data);
}
});
});
});
</script>
</body>
</html>
Results

First of all add jquery.min.js before add bootstrap js

Related

Select multiple items from one dropdown and insert into multiple rows of database

I want to allocate multiple individual courses to students with one row per student-course combination when the data is coming from a multi-select (checkboxes) field on a form. That is, the data is returned as a single result with multiple courses, and I want to split this up.
Short version: the teacher selects multiple courses from a single dropdown but I want to save data in multiple rows.
Here is my code.
<?php
$con = mysqli_connect('localhost','root');
mysqli_select_db($con,'sss_qr');
$q="select * from course_tb ";
$result=mysqli_query($con,$q);
?>
<!DOCTYPE html>
<html>
<head>
<title>Webslesson Tutorial | Bootstrap Multi Select Dropdown with Checkboxes using Jquery in PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/js/bootstrap-multiselect.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/css/bootstrap-multiselect.css" />
</head>
<body>
<br /><br />
<div class="container" style="width:600px;">
<h2 align="center">Bootstrap Multi Select Dropdown with Checkboxes using Jquery in PHP</h2>
<br /><br />
<form method="post" id="framework_form">
<div class="form-group">
<label>Select which Framework you have knowledge</label>
<select id="framework" name="framework[]" multiple class="form-control" >
<?php
if($result)
{
while($row=mysqli_fetch_array($result))
{
$course=$row["course_name"];
$code=$row["course_code"];
echo "<option value='$code'>$course</option>";
}
}
?>
</select>
</div>
<div class="form-group">
<input type="submit" class="btn btn-info" name="submit" value="Submit" />
</div>
</form>
<br />
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('#framework').multiselect({
nonSelectedText: 'Select Framework',
enableFiltering: true,
enableCaseInsensitiveFiltering: true,
buttonWidth:'400px'
});
$('#framework_form').on('submit', function(event){
event.preventDefault();
var form_data = $(this).serialize();
$.ajax({
url:"insert.php",
method:"POST",
data:form_data,
success:function(data)
{
$('#framework option:selected').each(function(){
$(this).prop('selected', false);
});
$('#framework').multiselect('refresh');
alert(data);
}
});
});
});
</script>
and insert.php file
<?php
$connect = mysqli_connect("localhost", "root", "", "sss_qr");
if(isset($_POST["framework"]))
{
$framework = '';
foreach($_POST["framework"] as $row)
{
$framework .= $row . ', ';
}
$framework = substr($framework, 0, -2);
$query = "INSERT INTO allocoursestudent(course_code) VALUES('".$framework."')";
if(mysqli_query($connect, $query))
{
echo 'Data Inserted';
}
}
?>
so i solve the problem by using this code.
<?php
$con = mysqli_connect("localhost", "root", "", "sss_qr");
$course=$_POST['course'];
if($course)
{
foreach($course as $c)
{
$q="INSERT INTO allocoursestudent(course_code) VALUES('".$c."')";
mysqli_query($con,$q);
}
}
?>
Firstly, you need to create a new table that pairs the student and the courses.
Secondly, you need to display students in the form (dropdown menu).
After that, you can do something like this:
<?php
$connect = mysqli_connect("localhost", "root", "", "sss_qr");
if(isset($_POST["course_code"])){
$course_code = mysqli_real_escape_string($con, $_POST["course_code"]);
$student_id = mysqli_real_escape_string($con, $_POST["student_id"]);
$query = "INSERT INTO new_table_name(course_code, student_id) VALUES";
for($i=0; $i<count($course_code); $i++){
$query .= " ('".$course_code[$i] ."', '".$student_id[$i]."'),";
}
$query = substr($query, 0, -1);
if(mysqli_query($connect, $query)){
echo 'Data Inserted #'.$i;
}
}
?>

what is my mistake with PHP AJAX DB?

I want to get information from a database, and I want to put it in selectbox as option.
I tried to do it but I could not not put it what is my mistake?(db can connect I just delete server name )
I am not sure how I can put db rows in selectbox as option.
therefore, I think my code has a problem.
p.php
<?php
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM test" ;
$result = mysqli_query($conn, $sql) or die("Query: ($sql) [problem]");
$row = mysqli_fetch_assoc($result);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_row($result)) {
display("<option value=$row[seat_id]>",$row[seatnumber]."\n");
}
display ("</select>", "\n");
} else {
echo "0 results";
}
mysqli_close($conn);
function display($tag , $value) {
echo $tag . $value ;
}
?>
p.html
<html>
<head>
<meta charset="utf-8">
<link href="" rel="stylesheet" type="text/css" />
</head>
<script type="text/javascript">
function transfer(){
var pix = document.getElementById('pix').value;
document.abc.test.value =pix;
}
</script>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js">
</script>
<script>
function ajaxWay() {
// syntax: $.post(URL,data,callback);
$.get("p.php", function(dataFromtheServer) {
$("#result").html(dataFromtheServer);
});
}
</script>
<body>
<div id="a" style="text-align:center;">
<form name="abc" method="get" action="p.php">
<select id='pix' onchange='ajaxWay()'>
<input type="button" value="click" onclick="transfer();">
<input type="text" name="test" id="test">
</form>
</div>
</body>
</html>
If your main problem is that you are not able to embed options into your HTML, try something like this:
<html>
<head>
<meta charset="utf-8">
<link href="" rel="stylesheet" type="text/css" />
</head>
<script type="text/javascript">
function transfer(){
var pix = document.getElementById('pix').value;
document.abc.test.value =pix;
}
</script>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js">
</script>
<script>
function ajaxWay() {
// syntax: $.post(URL,data,callback);
$.get("prefinal.php", function(dataFromtheServer) {
$("#result").html(dataFromtheServer);
});
}
</script>
<body>
<div id="a" style="text-align:center;">
<form name="abc" method="get" action="p.php">
<?php
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM test" ;
$result = mysqli_query($conn, $sql) or die("Query: ($sql) [problem]");
?>
<select id='pix' onchange='ajaxWay()'>
<?php
$row = mysqli_fetch_assoc($result);
if (mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_row($result))
{
echo '<option value="' . $row[0] . ">' . $row[0] . '</option>';
}
}
mysqli_close($conn);
?>
</select>
<input type="button" value="click" onclick="transfer();">
<input type="text" name="test" id="test">
</form>
</div>
</body>
</html>
Note that in the above I am using your code from p.php to generate the actual content for the select options. The form should NOT submit to p.php, but to some other script that will process the form and perform the required actions. I would help more if I knew more about what you were trying to achieve!

Page loading objects twice

The issue I'm experiencing is the code below seems to clone (duplicate) the form or any other HTML that loads on the page .
The first time I load the page the form appears as normal however when I type in the search text-box and delete all the characters the form displays twice (or any other HTML I place on the page)
How can it be possible to load the page without the form(s) or any other of the page contents repeated please?
<?php
include('..\db.php');
$con = mysqli_connect($dbsrvname, $dbusername, $dbpassword, $dbname);
$q1 = mysqli_query($con, "SELECT * FROM tbl1 username");
$data = "";
// if the search is true
if(isset($_POST['search']))
{
//
$var = $_POST['search'];
if ($query = mysqli_query($con,"SELECT username FROMtbl1 WHERE username LIKE '%$var%'"))
{
// possible creating duplicate results
while($row = mysqli_fetch_array($query))
{
$data .= '<div>' . $row['username'] . '</div>';
}
echo $data;
}
}
else
{
}
?>
<HTML>
<head>
<script src="https://code.jquery.com/jquery-3.0.0.js" integrity="sha256-jrPLZ+8vDxt2FnE1zvZXCkCcebI/C8Dt5xyaQBjxQIo=" crossorigin="anonymous"></script>
<script>
$(function() {
$('.input').keyup(function() {
var a = $('.input').val();
$.post('livesusers.php', { "search": a }, function(data) {
$('#display').html(data);
});
});
});
</script>
</head>
<body>
// form to input text and search
<h1>Search For User</h1>
<form action= "livesusers.php" method='POST'>
<input type="text" name="search" class='input'>
</form>
<div id='display' style='margin-top: 100px'></div>
</body>
The problem is because you're making an AJAX request to the current page. The response of the request includes the PHP code as well as the HTML below it, hence the current page is cloned in its entirety. To fix this, simply place your PHP code in its own file and make the AJAX request to that location. Try this:
response.php (name this whatever you like)
<?php
include('..\db.php');
$con = mysqli_connect($dbsrvname, $dbusername, $dbpassword, $dbname);
$q1 = mysqli_query($con, "SELECT * FROM tbl1 username");
$data = "";
// if the search is true
if(isset($_POST['search']))
{
//
$var = $_POST['search'];
if ($query = mysqli_query($con,"SELECT username FROMtbl1 WHERE username LIKE '%$var%'"))
{
// possible creating duplicate results
while($row = mysqli_fetch_array($query))
{
$data .= '<div>' . $row['username'] . '</div>';
}
echo $data;
}
}
else
{
}
?>
display.php
<!DOCTYPE HTML>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.0.0.js" integrity="sha256-jrPLZ+8vDxt2FnE1zvZXCkCcebI/C8Dt5xyaQBjxQIo=" crossorigin="anonymous"></script>
<script>
$(function() {
$('.input').keyup(function() {
var a = $('.input').val();
// change the page name below as required...
$.post('response.php', { "search": a }, function(data) {
$('#display').html(data);
});
});
});
</script>
</head>
<body>
<h1>Search For User</h1>
<form action= "livesusers.php" method='POST'>
<input type="text" name="search" class='input'>
</form>
<div id='display' style='margin-top: 100px'></div>
</body>
</html>
To make this even more robust you should consider changing your PHP code to return JSON instead of an unencoded string. See this question for a demonstration of how to do that.
The following code has an issue, it's adding data to itself twice!
$data .= $data . '<div>' . $row['username'] . '</div>';
Try this instead
$data .= '<div>' . $row['username'] . '</div>';

Data can not be inserted to the table

I have a db.php file which connection is established here to the database
<?php
$host = "localhost";
$user = "root";
$pass = "";
$db_name = "aigsonlinedb";
$con = new mysqli($host,$user,$pass,$db_name);
function formatDate($date){
return date('g:i a', strtotime($date));
}
?>
"Index.php" file here is a form where the data should be sent and retrieved from the database
<?php
include 'db.php';
?>
<!DOCTYPE html>
<html>
<head>
<title>Chat System in PHP</title>
<link rel="stylesheet" href="style.css" media="all"/>
<script>
function ajax(){
var req = new XMLHttpRequest();
req.onreadystatechange = function(){
if(req.readyState == 4 && req.status == 200){
document.getElementById('chat').innerHTML = req.responseText;
}
}
req.open('GET','chat.php',true);
req.send();
}
setInterval(function(){ajax()},1000);
</script>
</head>
<body onload="ajax();">
<div id="container">
<div id="chat_box">
<div id="chat"></div>
</div>
<form method="POST" action="index.php">
<input type="text" name="name" placeholder="enter name"/>
<textarea name="msg" placeholder="enter message"></textarea>
<input type="submit" name="submit" value="Send it"/>
</form>
<?php
if(isset($_POST['submit'])){
$name = $_POST['name'];
$msg = $_POST['msg'];
$query = "INSERT INTO chat (name,msg) VALUES ($name','$msg')";
$run = $con->query($query);
if($run){
echo "<embed loop='false' src='chat.wav' hidden='true' autoplay='true'/>";
}
}
?>
</div>
</body>
</html>
chat.php where the data is fetched from the database
<?php
include 'db.php';
$query = "SELECT * FROM chat ORDER BY id DESC";
$run = $con->query($query);
while($row = $run->fetch_array()) :
?>
<div id="chat_data">
<span style="color:green;"><?php echo $row['name']; ?></span> :
<span style="color:brown;"><?php echo $row['msg']; ?></span>
<span style="float:right;"><?php echo formatDate($row['date']); ?></span>
</div>
<?php endwhile;?>
The only problem is the data can not be sent to the database.
In the end of String ; vor SQL Statements. And PHP variables in double quotes and extra double quotes in values for define the datatype of sql

jquery auto-suggestion example doesn't work

This might be very easy for some of you but very hard for me since first time doing it.
By looking at some examples on the web, I ended up with the code below for auto-suggestion example but the code doesn't work.
Thanks
HTML
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#textbox_postcode').autocomplete(
{
source: 'search-db.php',
minLength: 3
});
});
</script>
</head>
<body>
<form action="search.php" method="post">
<input type="text" id="textbox_postcode" value="" /> <input type="submit" value="Search" />
</form>
</body>
</html>
PHP
$keyword = ltrim(strtolower(strip_tags($_GET['keyword'])));
if (! $keyword) return;
$host =
'localhost'; $user = 'root'; $pswd = ''; $dtbs = 'geomaps';
$host_conn = mysql_connect($host, $user, $pswd); $dtbs_conn =
mysql_select_db($dtbs);
$return = array();
$sql = "SELECT id, postcode FROM postcodes WHERE postcode LIKE
'$keyword%' ORDER BY postcode"; $run = mysql_query($sql);
if (#mysql_num_rows($run) == 0) return;
while ($records = mysql_fetch_array($run, MYSQL_ASSOC)) { $return[] =
$records; }
echo json_encode($return);
Try changing $_GET['keyword'] to $_GET['term']

Categories