Auto-fill input form with PHP, MySQL and jQuery - javascript

I had a problem with my auto-fill input form, with PHP MySQL and jQuery of course. So I have the select option form and some 'disabled' textboxes. And I want when I select the one of the option, the textboxes is auto-fill with value from the database
So there is my whole code :
PHP (Database connection) - I put it above my <html> code
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'db_mydatabase';
mysql_connect($host, $user, $pass);
mysql_select_db($db);
$user = '';
$query = mysql_query("SELECT * FROM tb_payment") or die (mysql_error());
?>
HTML
<select name="student" class="input-data">
<option value="">-- SELECT STUDENT --</option>
<!-- Do loop data from database -->
<?php while ($row = mysql_fetch_object($query)): ?>
<option value="<?php echo $row->id_user ?>">
<?php echo $row->name ?>
</option>
<?php endwhile; ?>
</select>
<br />
<table border=1>
<tr>
<th>ID</th>
<td><input type="text" class="output-id" disabled /></td>
</tr>
<tr>
<th>Name</th>
<td><input type="text" class="output-name" disabled /></td>
</tr>
<tr>
<th>Total Payment</th>
<td><input type="text" class="output-total" disabled /></td>
</tr>
</table>
jQuery :
$(document).ready(function(){
$(".input-data").on("change", function(){
<?php $id_user = "$(this).val()"; ?>
<?php $data = mysql_query("SELECT * FROM tb_payment WHERE id_user = '$id_user'") or die (mysql_error()); ?>
<?php while($row = mysql_fetch_object($data)): ?>
$(".output-id").val(<?php $row->id_user ?>);
$(".output-name").val(<?php $row->name ?>);
$(".output-total").val(<?php $row->total ?>);
<?php endwhile; ?>
});
});
But when i try to select the option, the values are wouldn't appear. Can someone help me?

What about creating new page name process.php contain:
require_once "connectDB.php";
header('Content-type: application/json; charset=utf-8');
if(isset($_POST['one'])){
$json = array();
$id = trim($_POST['one']);
$query = "SELECT id, name, total FROM tb_payment WHERE id_user = ?";
$statement = $databaseConnection->prepare($query);
$statement->bind_param('s', $id);
$statement->execute();
$statement->bind_result($nId, $nName, $nTotal);
while ($statement->fetch()){
$user=array('id'=>$nId,'name'=>$nName,'total'=>$nTotal);
array_push($json,$user);
}
echo json_encode($json, true);
}
And the Jquery:
$(document).ready(function(){
$(".input-data").on("change", function(){
var id = $(".input-data").val();
var data = 'one=' + id;
$.ajax({
type: "POST",
url: "process.php",
data: data,
dataType: 'json',
success: function (data) {
if (data) {
for (var i = 0; i < data.length; i++) { //for each user in the json response
$(".output-id").val(data[i].id);
$(".output-name").val(data[i].name);
$(".output-total").val(data[i].total);
} // for
} // if
} // success
}); // ajax
});
});

You have to print
$(".output-id").val(<?php print $row->id_user ?>);
$(".output-name").val(<?php print $row->name ?>);
$(".output-total").val(<?php print $row->total ?>);

Related

Deleting row from mysql using jquery and php

I want to create delete feature using function and jquery
My jquery works and show messages but nothing happen "Nothing Deleted"
Jquery Code
<script type="text/javascript">
$(".remove").click(function(){
var id = $(this).parents("tr").attr("id");
if(confirm('Are you sure to remove this record?'))
{
$.ajax({
url: 'delete.php',
type: 'GET',
data: {id: id},
error: function() {
alert('Something is wrong');
},
success: function(data) {
$("#"+id).remove();
alert("Record removed successfully");
}
});
}
});
PHP Function Code
function delete($table,$id) {
global $connect;
mysqli_query($connect, "DELETE FROM `$table` WHERE `id` = $id ");
}
Delete.php Code
include ('function.php');
$id = $_GET['id'];
$table = 'msg';
delete($table,$id);
HTML Code
<table class="table table-striped" style="background-color: #ffffff;">
<tr>
<th>ID</th>
<th>From</th>
<th>Title</th>
<th>Date</th>
<th>Action</th>
</tr>
<?php
$i = '1';
$username = $user_data['username'];
$query = "SELECT * FROM msg WHERE `go_to` = '$username' Order by id";
$result = mysqli_query($connect, $query);
while($row = mysqli_fetch_assoc($result))
{
?>
<tr>
<td><?php echo $i++; ?></td>
<td><?php echo $row['come_from']; ?></td>
<td>
<a href="read_message/<?php echo $row['id']; ?>"><?php if(count_msg_not_opened($username, $row['id']) > '0')
{
echo $row['title'];
}
else
{
echo '<b>' . $row['title'] . '</b>';
} ?></a></td>
<td><?php echo $row['date']; ?></td>
<td>
<button class="btn btn-danger btn-sm remove">Delete</button>
</td>
</tr>
<?php } ?>
</table>
I also include "jquery.min.js"
When I press "Delete" bottom this message appears "Are you sure to remove this record?"
I pressed "Yes" then this message appears "Record removed successfully", but nothing was deleted.
I don't know where the problem is.
You forgot to add the id attribute to the <tr>
<tr id="<?php echo $row['id']; ?>">
You should also add error checking and prepared statements to your PHP code.
Are you sure that you have connected your PHP-code to your SQL-database?
function delete($table,$id) {
global $connect;
mysqli_query($connect, "DELETE FROM `$table` WHERE `id` = $id ");
}
The code above is relying on a connection already existing within your PHP-file. See this to find out how to apply a connection.

When a user pick a speaker name on a dropdown list only the speakers expertise will show in the next topic dropdown list

What i want to achieved is when a user pick or choose a speaker name on a dropdown list only the speaker expertise will show up in the next topic dropdown list. Ex. When He choose Ms. Cimatu the topic dropdown list must only show the topics that Ms. Cimatu is familiar like Motivational, Entertainment, Healtcare. And When the user choose Mr. Santos the topic dropdown list must only show the topics that he know like Business, and Technology. Btw the speakers names and topics that is show on the dropdown list is from a database that i get using select query and mysqli_fetch_array. Please guys any suggestions and help is really appreciated.
I already try this solution but my problem in this code is when i add new speaker, when i select their name it will not show any topics.
<?php
$conn = new mysqli($servername, $username, $password, $dbname);
$selectspeakers = "SELECT * FROM speakers";
$sp_result = mysqli_query($conn, $selectspeakers);
$result = mysqli_query($conn, "SELECT speaker_fullname FROM speakers");
$storeArray = Array();
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
$storeArray[] = $row['speaker_fullname'];
}
$msCimatuTopics = "SELECT speaker_specialization1, speaker_specialization2, speaker_specialization3, speaker_specialization4, speaker_specialization5 FROM speakers WHERE speaker_fullname = '$storeArray[0]' ";
$msCimatuTopics_result = mysqli_query($conn, $msCimatuTopics);
$mrSantosTopics = "SELECT speaker_specialization1, speaker_specialization2, speaker_specialization3, speaker_specialization4, speaker_specialization5 FROM speakers WHERE speaker_fullname ='$storeArray[1]' ";
$mrSantosTopics_result = mysqli_query($conn, $mrSantosTopics);
?>
<html>
<head>
</head>
<body>
<div class="form-group">
<label for="speaker">Preferred Speaker:</label>
<select name="speaker" class="form-control" id="speaker" style='text-transform:capitalize;'>
<?php while($array = mysqli_fetch_array($sp_result)):;?>
<option value = "<?php echo $array['speaker_fullname'];?>" <?php if($_SESSION["selectedSpeaker"] == $array['speaker_fullname']) echo "selected";?> ><?php echo $array['speaker_fullname'];?></option>
<?php endwhile;?>
</select>
</div>
<div class="form-group">
<label for="msCimatuTopics" id="topicTitle" class="hidden">Topic:</label>
<select name="topic" class="form-control hidden" id="msCimatuTopics" style='text-transform:capitalize;' autofocus required="required">
<?php $array = mysqli_fetch_array($msCimatuTopics_result);?>
<option value = "" <?php if($_SESSION["selectedSpeaker"] == $array['speaker_fullname']) echo "selected";?> >Please Select...</option>
<option value = "<?php echo $array['speaker_specialization1'];?>" <?php if ($_POST['topic'] == $array['speaker_specialization1']) echo 'selected="selected"';?> <?php if($_SESSION["selectedSpeaker"] == $array['speaker_fullname']) echo "selected";?> ><?php echo $array['speaker_specialization1'];?></option>
<option value = "<?php echo $array['speaker_specialization2'];?>" <?php if ($_POST['topic'] == $array['speaker_specialization2']) echo 'selected="selected"';?> <?php if($_SESSION["selectedSpeaker"] == $array['speaker_fullname']) echo "selected";?> ><?php echo $array['speaker_specialization2'];?></option>
<option value = "<?php echo $array['speaker_specialization3'];?>" <?php if ($_POST['topic'] == $array['speaker_specialization3']) echo 'selected="selected"';?> <?php if($_SESSION["selectedSpeaker"] == $array['speaker_fullname']) echo "selected";?> ><?php echo $array['speaker_specialization3'];?></option>
<option value = "<?php echo $array['speaker_specialization4'];?>" <?php if ($_POST['topic'] == $array['speaker_specialization4']) echo 'selected="selected"';?> <?php if($_SESSION["selectedSpeaker"] == $array['speaker_fullname']) echo "selected";?> ><?php echo $array['speaker_specialization4'];?></option>
<option value = "<?php echo $array['speaker_specialization5'];?>" <?php if ($_POST['topic'] == $array['speaker_specialization5']) echo 'selected="selected"';?> <?php if($_SESSION["selectedSpeaker"] == $array['speaker_fullname']) echo "selected";?> ><?php echo $array['speaker_specialization5'];?></option>
</select>
<select name="topic" class="form-control hidden" id="mrSantosTopics" style='text-transform:capitalize;' autofocus required="required">
<?php $array = mysqli_fetch_array($mrSantosTopics_result);?>
<option value = "" <?php if($_SESSION["selectedSpeaker"] == $array['speaker_fullname']) echo "selected";?> >Please Select...</option>
<option value = "<?php echo $array['speaker_specialization1'];?>" <?php if ($_POST['topic'] == $array['speaker_specialization1']) echo 'selected="selected"';?> <?php if($_SESSION["selectedSpeaker"] == $array['speaker_fullname']) echo "selected";?> ><?php echo $array['speaker_specialization1'];?></option>
<option value = "<?php echo $array['speaker_specialization2'];?>" <?php if ($_POST['topic'] == $array['speaker_specialization2']) echo 'selected="selected"';?> <?php if($_SESSION["selectedSpeaker"] == $array['speaker_fullname']) echo "selected";?> ><?php echo $array['speaker_specialization2'];?></option>
<option value = "<?php echo $array['speaker_specialization3'];?>" <?php if ($_POST['topic'] == $array['speaker_specialization3']) echo 'selected="selected"';?> <?php if($_SESSION["selectedSpeaker"] == $array['speaker_fullname']) echo "selected";?> ><?php echo $array['speaker_specialization3'];?></option>
<option value = "<?php echo $array['speaker_specialization4'];?>" <?php if ($_POST['topic'] == $array['speaker_specialization4']) echo 'selected="selected"';?> <?php if($_SESSION["selectedSpeaker"] == $array['speaker_fullname']) echo "selected";?> ><?php echo $array['speaker_specialization4'];?></option>
<option value = "<?php echo $array['speaker_specialization5'];?>" <?php if ($_POST['topic'] == $array['speaker_specialization5']) echo 'selected="selected"';?> <?php if($_SESSION["selectedSpeaker"] == $array['speaker_fullname']) echo "selected";?> ><?php echo $array['speaker_specialization5'];?></option>
</select>
</div>
</body>
</html>
<script>
$('#speaker').change(function(){
var selected_item = $(this).val()
if(selected_item == "Ms. Cimatu")
{
$('#msCimatuTopics').val("").removeClass('hidden')
$('#topicTitle').val("").removeClass('hidden');
$('#mrSantosTopics').val(selected_item).addClass('hidden');
}
else if(selected_item == "Mr. Santos")
{
$('#mrSantosTopics').val("").removeClass('hidden')
$('#topicTitle').val("").removeClass('hidden');
$('#msCimatuTopics').val(selected_item).addClass('hidden');
}
else
{
$('#msCimatuTopics').val(selected_item).addClass('hidden');
$('#mrSantosTopics').val(selected_item).addClass('hidden');
$('#topicTitle').val(selected_item).addClass('hidden');
}
});
</script>
this is the image of dropdown list
This is the image of the database data
There are some basic things you can look to improve with your implementation. The biggest is you don't need to keep querying the same table for different pieces of data. If you are okay with running the SELECT * on the speakers table then you can skip the rest of your queries.
The next task is to try and make your code less dependent on singular values. If you notice you are writing the same code for value 1, value 2, etc then try to think about how to abstract your code so that it can work for an unlimited number of values.
This is a very rough implementation based on your sample code implementing the items I've mentioned. I have no way of testing it so there may be some small errors you need to debug before it works for your purpose:
<?php
// Based on your code and image these appear to be the fields in the speakers table:
// speaker_fullname
// speaker_image
// speaker_videolink
// speaker_specialization1
// speaker_specialization2
// speaker_specialization3
// speaker_specialization4
// speaker_specialization5
// Make your connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Get speakers and all their data (you only need one query!)
$result = mysqli_query($conn, "SELECT * FROM speakers");
// Store the speakers for later
// (You could maybe use this instead but depends on your PHP version:)
// -> http://php.net/manual/en/mysqli-result.fetch-array.php
$speaker_array = array();
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$speaker_array[] = $row;
}
// Apparently you have session values? You don't start the session though?
// See: http://php.net/session_start
$session_speaker_fullname = ( ! empty($_SESSION["selectedSpeaker"])) ? $_SESSION["selectedSpeaker"] : '';
?>
<html>
<head>
</head>
<body>
<div class="form-group">
<label for="speaker">Preferred Speaker:</label>
<select name="speaker" class="form-control" id="speaker" style='text-transform:capitalize;'>
<option value=""></option>
<?php foreach($speaker_array as $row):;?>
<option value="<?php echo $row['speaker_fullname'];?>"
<?php if($session_speaker_fullname == $row['speaker_fullname']) echo "selected";?>
><?php echo $row['speaker_fullname'];?></option>
<?php endforeach;?>
</select>
</div>
<div class="form-group">
<label for="topic" id="topicTitle" class="hidden">Topic:</label>
<select name="topic" class="form-control" id="topic" style='text-transform:capitalize;' autofocus required="required">
<!-- this will get populated via JavaScript -->
</select>
</div>
<script type="text/javascript">
// Let your data be used by JavaScript
var speaker_array = <?php echo json_encode($speaker_array); ?>;
// A function to update the topic select
function update_topic_select_list() {
// Clear the current topic list
$('#topic').html('');
// Only re-build the topic list if a speaker is selected
if ($('#speaker option:selected').val() != '') {
var topic_array = Array();
// Find the correct speaker
for (var i = 0; i < speaker_array.length; i++) {
// The speaker name matches
if (speaker_array[i].speaker_name == $('#speaker option:selected').val())
// Add the values to the topic array
topic_array.push(speaker_array[i].speaker_specialization1);
topic_array.push(speaker_array[i].speaker_specialization2);
topic_array.push(speaker_array[i].speaker_specialization3);
topic_array.push(speaker_array[i].speaker_specialization4);
topic_array.push(speaker_array[i].speaker_specialization5);
// Stop the loop
break;
}
}
// Update the topic list
for (var i = 0; i < topic_array.length; i++) {
// Don't add empty values
if (topic_array[i] != '') {
$('#topic').append('<option value="' + topic_array[i] + '">' + topic_array[i] + '</option>');
}
}
}
}
// Watch for changes to the speaker selection
$('#speaker').change(function() {
// Do you need to do anything else?
// Call the update function
update_topic_select_list();
});
// Force a change trigger after page load - in case you need that session value set?
$('#speaker').trigger('change');
</script>
</body>
</html>
I would suggest to use AJAX. In this way, when the user selects a speaker, Javascript will request the server the list of specializations for the selected speaker. For example:
<!-- This is your <select> of speakers -->
<select id="select-speaker">
<?php echo($speaker_options); ?>
</select>
<!-- This is your <select> of specializations -->
<select id="select-specialization">
<option value=""></option>
</select>
<!-- This is your JS code -->
<script>
// When users select the speaker, #select-specialization gets updated
$("#select-speaker").change(function (){
var speaker = document.getElementById("select-speaker");
GetSpecializations(speaker.value).then(function (data){
document.getElementById("select-specialization").innerHTML = data;
});
});
async function GetSpecializations(speaker){
// Request the server via AJAX the list of specializations for that speaker
var options = await AjaxPOST("page.php", speaker);
// Returns something like "<option value='spec1'>Spec1</option>..."
return options;
}
</script>
This is just an idea. Here's a possible implementation of AjaxPOST():
function AjaxPOST(url, speaker){
return new Promise(resolve => {
var http = new XMLHttpRequest();
var params = {"sentFromAJAX" : "true", "speaker" : speaker};
http.onreadystatechange = function (){
if (this.readyState == 4 && this.status == 200){
resolve(this.responseText);
}
};
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/json; charset=utf-8");
http.send(JSON.stringify(params));
});
}
This is a basic AJAX tutorial from W3C and this is a useful article on async/await from MDN.
P.S.: I didn't test this code. But it should work.
P.P.S.: It's missing the PHP part of code. You have to handle AJAX requests sent from Javascript. Note that this code sends the params encoded in JSON, so in PHP you have to retrieve $_POST variable using something like: $_POST = json_decode(file_get_contents("php://input"), true) ?: [];.

ajax delete post asynchronously - php

I'm trying to create a add/delete/edit post system using php for a website. I have the add working, so when the user enters in information it gets added to the database and then asynchronously gets added onto the page using ajax. I want a similar function that deletes asynchronously as well. Right now, when I click delete, only the oldest post gets deleted AFTER refreshing the page. It does not delete the post as soon as I click the delete button which is my goal. This is what I have so far. The home.php is where my form is that collects the information and also prints out the information from the database. handledelete.php is where the deleting is handled.
home.php
<script>
$(function() {
$('#deleteButton').click(function(event) {
event.preventDefault();
$.ajax({
type: "GET",
url: "handle_delete.php",
data : { entry_id : $(this).attr('data-id') },
beforeSend: function(){
}
, complete: function(){
}
, success: function(html){
$("#show_entries").append(html);
}
});
});
});
</script>
<div id="entry">
<form method="GET" action="handle_insert.php">
<table align="center" width="30%" border="0">
<tr>
<td><input type="text" name="activity" id="activity" placeholder="Activity" required /></td>
</tr>
<tr>
<td><input type="text" name="duration" id="duration" placeholder="Duration (hours)" required /></td>
</tr>
<tr>
<td><input type="text" name="date" id="date_" placeholder="Date (YYYY-MM-DD)" required /></td>
</tr>
<tr>
<td><button type="submit" name="submitButton" id="submitButton">Add input</button></td>
</tr>
</table>
</form>
</div>
<!-- shows the previous entries and adds on new entries-->
<div id="show_entries">
<?php
$userID = $_SESSION["user"];
$link = mysqli_connect('localhost', 'oviya', '', 'userAccounts');
$query="SELECT * FROM dataTable WHERE user_id='$userID'";
$results = mysqli_query($link,$query);
while ($row = mysqli_fetch_assoc($results)) {
echo '<div class="output" >';
$entry_id = $row["entry_id"];
$output= $row["activity"];
echo "Activity: ";
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8')."<br>"."<br>";
$output= $row["duration"];
echo "Duration: ";
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8')." hrs"."<br>"."<br>";
$output= $row["date_"];
echo "Date: ";
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8')."<br>"."<br>";
echo '<button type="submit" name="deleteButton" data-id='.$entry_id.' id= "deleteButton">Delete</button>';
//echo '<button type="submit" name="editButton" data-id='.$entry_id.' id="editButton">Edit</button>';
echo '</div>';
}
?>
</div>
handle_delete.php
session_start();
$user = 'oviya';
$password = '';
$db = 'userAccounts';
$host = 'localhost';
$port = 3306;
$link = mysqli_connect($host, $user, $password, $db);
mysqli_query($link,"GRANT ALL ON comment_schema TO 'oviya'#'localhost'");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if(!empty($_GET["entry_id"])){
$entry_id = mysqli_real_escape_string($link, $_GET["entry_id"]);
$sql = "DELETE FROM dataTable WHERE entry_id = '$entry_id'";
$result = mysqli_query($link, $sql);
die();
mysqli_close($link);
}
This line is the problem. It would add elements if your AJAX call were returning HTML, which it isn't:
$("#show_entries").append(html);
Instead, you want to remove the deleted element, which you can reference directly and remove from the DOM:
$('#deleteButton').click(function(event) {
event.preventDefault();
// Get a reference to the whole row element.
var row = $(this).parent();
$.ajax({
type: "GET",
url: "handle_delete.php",
data : { entry_id : $(this).attr('data-id') },
success: function(html){
// Remove the row
row.remove();
}
});
});

onChange function change the displayed data from a table

I have a table in my website and a dropdown list in my website which according to the selected value from the dropdown list it will change the output of the table.
I did a search and I found this on stackoverflow and I tried to do something similar but it doesn't work. Here is my php file called announcements which I want to display the table.
<?php
include_once 'header.php';
$connection = mysql_connect("localhost", "root", "smogi")?>
<html>
<head>
<script type="text/javascript" src="javascript.js"></script>
</head>
<body>
<?php
$result = queryMysql("SELECT * FROM doctor WHERE username='$username'");
if (mysql_num_rows($result)):
?>
<!-- Koumpi pou se metaferei sti selida gia tin dimiourgia neas anakoinwseis -->
<form action="new_announcement.php">
<input type="submit" value="Create New Announcement">
</form>
<br />
Select Category :<select id="SelectDisease" name="category">
<option value="*">All</option>
<!--emfanizei tis epiloges gia ta specialties me basi auta p exoume sti basi mas -->
<?php
$sql = mysql_query("SELECT name FROM disease");
while ($row = mysql_fetch_array($sql)) {
echo "<option value='" . $row['name'] . "'>" . $row['name'] . "</option>";
}
?>
</select><br><br />
<table border="1" style="width:100%">
<tr>
<td><b>Author</b></td>
<td><b>Category</b></td>
<td><b>Subject</b></td>
<td><b>Content</b></td>
</tr>
<?php
if(isset($_GET["selected"])){
$type = $_GET["selected"];
$query = "SELECT author,category,subject,content FROM announcements WHERE category='" . $type . "'";
$announcements = mysql_query($query, $connection);
$counter = 0;
$z = 0;
if ($announcements == FALSE) {
die(mysql_error()); // To get better errors report
}
while ($row = mysql_fetch_assoc($announcements)) {
while ($row = mysql_fetch_assoc($announcements)) {
$counter++;
?>
<tr>
<td><?php echo $row['author'];?></td>
<td><?php echo $row['category']; ?></td>
<td><?php echo $row['subject']; ?></td>
<td><?php echo $row['content']; ?></td>
</tr>
<?php }
}
}
?>
<?php
else:
?>
Select Category :<select id="SelectDisease" name="category">
<option value="*">All</option>
<!--emfanizei tis epiloges gia ta specialties me basi auta p exoume sti basi mas -->
<?php
$sql = mysql_query("SELECT name FROM disease");
while ($row = mysql_fetch_array($sql)) {
echo "<option value='" . $row['name'] . "'>" . $row['name'] . "</option>";
}
?>
</select><br><br />
<table border="1" style="width:100%">
<tr>
<td><b>Author</b></td>
<td><b>Category</b></td>
<td><b>Subject</b></td>
<td><b>Content</b></td>
</tr>
<?php
if(isset($_GET["selected"])){
$type = $_GET["selected"];
$query = "SELECT author,category,subject,content FROM announcements WHERE category='" . $type . "'";
$announcements = mysql_query($query, $connection);
$counter = 0;
$z = 0;
while ($row = mysql_fetch_assoc($announcements)) {
$counter++;
?>
<tr>
<td><?php echo $row['author'];?></td>
<td><?php echo $row['category']; ?></td>
<td><?php echo $row['subject']; ?></td>
<td><?php echo $row['content']; ?></td>
</tr>
<?php } } endif;?>
</table>
</body>
</html>
And this is my javascript.js file
$(document).ready(function() {
$('#SelectDisease').change(function() {
var selected=$(this).val();
$.get("announcements.php?selected="+selected, function(data){
$('.result').html(data);
});
});
});
Thank you for your time :)
PS: THE INCLUDE_ONCE CODE create the connection with th db
First thing is that unless your user makes a selection, you do not have any $_GET available so it will be undefined. You should get the value if it is available. Like so:
if(isset($_GET['selected'])){
$type = $_GET['selected'];
}
But this is not the only issue here. $.get is an ajax request and it is just sending a request to your php file and gets all the html content of your page.
If you do not care to reload the page each time your user selects an option, instead of an $.get request simply redirect your user to that url. Otherwise if you want to do it without reloading, you need to do an $.get request correctly.
The example that you said you are trying to do something similar, is not sending an $.get request to the same page that the user is viewing. It is sending the get request to another php page which is just designed to get the $_GET["selected"] from its url, send a query to the database, get the result from the database and then just return the result, which will be the data in your $.get request.
See this example: Get data from mysql database using php and jquery ajax
It is trying to do the same thing as you, except with $.POST which you can do the same or change it to a $.GET if you want. See how the other php page return the result and how the $.get request is receiving and viewing the data.
mysql_query() will result in FALSE which is Boolean value if there is any error, do check before while loop, to get better error,
if($announcements == FALSE) {
die(mysql_error()); // To get better errors report
}
while($row = mysql_fetch_assoc($announcements)){
// then you code here
}
mysql_query() returns FALSE in case of error.
You have to choose the data base name.
Like so:
$connection = mysql_connect("localhost", "root", "smogi", "***DATABASE_NAME***");
Remember, mysql functions are deprecated!
Use mysqli or PDO.
Have a nice day

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