Ajax- fill multiple textboxes for php - javascript

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

Try to modify you JS code similar to this:
function popBox(selectValue) {
$.ajax({
type: 'POST',
url: "PopulateBoxes.php",
data: { dat: selectedValue },
success: function(serverResponse) {
// after success request server should return response with data
// that will be passed to this callback function as parameter
// and you can use it to fill text boxes:
$('#txt_Duration').val(serverResponse.duration);
}
});
}
Also you should modify your PHP code to return data in JSON:
// At the end you should return selected array. For example:
echo json_encode($dataArray); exit;

As you are using $_POST in your PHP code, you would need to edit the ajax call script.
Type is either GET or POST and page address comes in to the url attribute.
$.ajax({
type: 'POST',
url: "PopulateBoxes.php",
data: { dat: str}
}).done(function( msg ) { //you can also use success
alert( "Data Saved: " + msg );
});
}

Related

How do I create a delete button where I can delete the list at the side of my database?

enter image description here
How do I create a delete button where I can delete the list at the side of my database?
I'm trying to get the 'x' or delete button as shown in the picture
This is my current code:
<html>
<head>
<link rel="stylesheet" href="css/booklist.css">
<title>Search data by its ID</title>
<script type="text/javascript">
function out() {
alert("Checkout Items Successful!");
}
</script>
</head>
<div class="background">
<h1>Library Checkout System</h1>
<h2>Loan/Request Your Books Here</h2>
<form action="" method="POST">
<input type="text" name="id" placeholder="Please enter Book ID" />
<input type="submit" name="search" value="Search By ID" />
</form>
<table border="2" id="newton">
<tr>
<th>Product Name</th>
<th>Quantity</th>
<th>Returned Date</th>
</tr><br><br>
<?php
$connection = mysqli_connect("localhost","root", "");
$db = mysqli_select_db($connection,"myfirstdb");
session_start();
if (!isset($_SESSION['id'])) {
$_SESSION['id'] = array();
}
if(isset($_POST['search']))
{
$id = $_POST['id'];
array_push($_SESSION['id'],$id); //Here we have declared a session array. We can add elements to it by array_push function.//
$_SESSION['id'] = array_unique($_SESSION['id']); //array_unique: Removes duplicate values from an array
$id = implode(',',$_SESSION['id']); //implode : returns a strings from the elements of an array.//
// instead of changing the database of each row, the implode() function adds the rows according to the selected id entered.//
// this function is the key for solving my original problem.//
$query = "SELECT * FROM `table3` where id in ($id)";
$query_run = mysqli_query($connection, $query);
while($row = mysqli_fetch_array($query_run))
{
?>
<tr>
<td>
<?php echo $row ['product_name']; ?> </td>
<td>
<?php echo $row ['quantity']; ?> </td>
<td>
<?php echo $row ['returned_date']; ?> </td>
</tr>
<?php
}
}
?>
</table>
<br>
<input type="submit" name="send" value="Confirm Booklist" onclick="out()" />
</form>
</div>
</body>
</html>
How do I create a delete button where I can delete the list at the side of my database?
I'm trying to get the 'x' or delete button as shown in the picture

Displaying data from select box without clicking button

I made this work already but somehow it stopped working. I want to display informations from database related to the chosen data from the select box without clicking a button so I used ajax.
The button "Approve Clearance" is used for another action which is I wished to used after the display of data.
There is a div with id #records which is hidden and will show upon display of data.
<div class="card-body">
<form id="gform" action="action/actionclearance.php" method="POST">
<label>Student ID</label>
<select id="stud_id" name="stud_id" class="form-control col-md-6" required>
<option selected="selected">Select Student ID</option>
<?php
$mysqli = new mysqli ('localhost', 'u220931635_arug', 'Smarvcdsl2019', 'u220931635_arug') or die (mysqli_error($mysqli));
$resultset = mysqli_query($mysqli, "SELECT * FROM tbl_student where delete_flag = 0");
while( $rows = mysqli_fetch_assoc($resultset) ) {
?>
<option><?php echo $rows["stud_id"]; ?></option>
<?php } ?>
</select>
<br>
<button type="submit" class="btn btn-primary btn-md" name="gclear" id="gclear" class="gclear"><i class="fas fa-check-double"></i> Approve Clearance</button>
</form>
</div>
<div class="card-footer">
<div id="display">
<div class="row" id="heading" style="display:none;">
<tr>
<th class="text-center">
<div class="col-sm-6">
<strong>Student</strong>
</div>
</th>
</tr>
</div>
<div class="row" id="records">
<tr>
<td>
<div class="col-sm-6">
<span id="stud_fname"></span>
<span id="stud_mname"></span>
<span id="stud_lname"></span>
<span id="stud_suffix"></span>
</div>
</td>
</tr>
</div>
<div class="row" id="no_records">
<div class="col-lg-12 text-center">
Plese select Student ID to view details</div>
</div>
</div>
</div>
</div>
Below is the ajax code I used to display data without clicking a button.
<script>
$(document).ready(function(){
// code to get all records from table via select box
$("#stud_id").change(function() {
var id = $(this).find(":selected").val();
var dataString = 'stud_id='+ id;
$.ajax({
url: 'getstudent.php',
dataType: "json",
data: dataString,
cache: false,
success: function(studentData) {
if(studentData) {
$("#heading").show();
$("#no_records").hide();
$("#stud_fname").text(studentData.stud_fname);
$("#stud_mname").text(studentData.stud_mname);
$("#stud_lname").text(studentData.stud_lname);
$("#stud_suffix").text(studentData.stud_suffix);
$("#records").show();
} else {
$("#heading").hide();
$("#records").hide();
$("#no_records").show();
}
}
});
});
});
</script>
This is the getstudent.php which is connected to the database where ajax gets datas to display.
<?php
include("../configAdmin.php");
if($_REQUEST['stud_id']) {
$mysqli = new mysqli ('localhost', 'u220931635_arug', 'Smarvcdsl2019', 'u220931635_arug') or die (mysqli_error($mysqli));
$resultset = mysqli_query($mysqli, "SELECT * FROM tbl_student where delete_flag = 0 AND stud_id ='".$_REQUEST['stud_id']."'");
while( $rows = mysqli_fetch_assoc($resultset) ) {
$data = $rows;
}
echo json_encode($data);
} else {
echo 0;
}
?>
without using ajax you can do this
<select id="stud_id" name="stud_id" class="form-control col-md-6" required>
<option selected="selected">Select Student ID</option>
<?php
$mysqli = new mysqli ('localhost', 'u220931635_arug', 'Smarvcdsl2019', 'u220931635_arug') or die (mysqli_error($mysqli));
$resultset = mysqli_query($mysqli, "SELECT * FROM tbl_student where delete_flag = 0");
while( $rows = mysqli_fetch_assoc($resultset) ) {
?>
<option value="<?php echo $rows["stud_id"]; ?>"><?php echo $rows["stud_id"]; ?></option>
<?php } ?>
</select>

how do i make my table output appear only when i click on the search button

how do i make my table output appear only when i click on the search button
<?php
require_once 'includes/header.php';
if ($_POST) {
$list = $_POST['categoryList'];
if ( $list != "") {
$sql = "SELECT product.product_name, product.product_image, product.category_id, product.active, category.category_name FROm product
INNER JOIN category on product.category_id = category.category_id
WHERE product.category_id = '".$_POST['categoryList']."' AND product.active = 1";
$result = $connect ->query($sql);
}
/*else{
$msg = echo 'Select category';
}*/
}
?>
HERE i am running a php script to pull data from the database table product
<div class="row">
<div class="col-md-12">
<div class="card mt-5" style="width: 30rem; margin-left: 25%" >
<div class="card-header bg-dark text-light"><span class="glyphicon glyphicon-th-list"></span> Categories </div>
<div class="card-body">
<form action="" method="post" enctype="multipart/form-data">
<div class="form-group row mt-5 ml-5">
<label for="categoryList" class="col-sm-8 col-form-label">Category Name</label>
<div class="col-sm-8">
<select class="form-control" id="categoryList" name="categoryList">
<option value="">--Select--</option>
<?php
$sql= "SELECT category_id, category_name FROM category where category_status = 1 AND category_status = 1";
$result =$connect->query($sql);
while ($row = $result->fetch_array()) {
echo '<option value="'.$row[0].'">'.$row[1].'</option>';
}
?>
</select>
</div>
</div>
<div class="col">
<button type="submit" onclick="myFunction()" class="btn btn-dark" id="searchButton" style="margin-left: 100px">Search </button>
</div>
</form>
</div>
This is the part where i select the categories pulled from the database
</div>
</div>
</div>
<div id="myDiv">
<table class="table" id="myTable">
<thead class="thead thead-dark">
<th>Photo</th>
<th>Name</th>
<th>Category</th>
</thead>
<tbody>
<?php
#$sql = "SELECT product.product_name, product.product_image, product.category_id, product.active, category.category_name FROM product
INNER JOIN category on product.category_id = category.category_id
WHERE product.category_id = '".$_POST['categoryList']."' AND product.active = 1";
$result = $connect ->query($sql);
while($row = $result->fetch_assoc())
{
$imageUrl = substr($row['product_image'], 3);
$name = $row['product_name'];
$category = $row['category_name'];
?>
<tr>
<td><?php echo '<img class="img-round" src='.$imageUrl.' style="height:30px; width:50px;">'?></td>
<td><?php echo $name?></td>
<td><?php echo $category?></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
THIS IS THE TABLE THAT DISPLAYS THE PRODUCTS ON IN THE SELECTED CATEGORY ABOVE
<script>
$("#navDashboard").addClass('active');
$("#myTable").DataTable();
</script>
THIS IS THE SCRIPT RESPONSIBLE FOR DATATABLE AND ACTIVE NAVBAR
generally what I am doing is using ajax. give your form an id . for example en ajax call after submitting button
$(document).on('submit', '#show_table', function () {
event.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
type: 'POST',
url: 'your_file.php',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: (
function (formData) {
$(".result").html(formData)
}
)
});
});
in the URL pass the name of the file where the call will be made (create a new file). the value from the search input will pass in POST TYPE and then run your query . as you can see the result will display in a div with a class of result. so in the search page create a div
and the table will appear there .
the page will not be refreshed based on the event.preventDefault();
hope this give you any help :)

submit form not working/ not reload

i create a form(form1) to search mysql data into table without reload the page using ajax, it's working fine, but when i want to insert data from the second form(formorder) the submit button not refresh or reload.
this my code
index.php
<html>
<head>
<title>Search Data Without Page Refresh</title>
<script type='text/javascript' src='js/jquery-1.4.2.min.js'></script>
</head>
<body>
<center>
<br>
<?php include("koneksi1.php");
$sql="select * from supplier";
$query=mysqli_query($koneksi,$sql);
?>
<form action="" name = "form1">
<select name="namea" style="width:300px; padding:8px;">
<?php
while($data=mysqli_fetch_assoc($query)){
echo "<option value='".$data['id_supplier']."'>".$data['id_supplier']."</option>";
}
?>
</select>
<input type="submit" value="Search" id="search-btn" style="padding:8px;"/>
</form>
<br>
<div id = "s-results">
<!-- Search results here! -->
</div>
<script type = "text/javascript">
$(document).ready(function(){
$('#s-results').load('search.php').show();
$('#search-btn').click(function(){
showValues();
});
$(function() {
$('form').bind('submit',function(){
showValues();
return false;
});
});
function showValues() {
$.post('search.php', { namea: form1.namea.value },
function(result){
$('#s-results').html(result).show();
});
}
});
</script>
</center>
</body>
</html>
search.php
<?php
include("koneksi1.php");
isset( $_REQUEST['namea'] ) ? $name=$_REQUEST['namea'] : $name='';
$name = mysqli_real_escape_string($koneksi,$name);
if( empty( $name )){
echo '<script> alert("Please search something!")</script>';
}else{
$sql = "select * from barang where id_supplier like '%$name%'";
$rs = mysqli_query($koneksi,$sql ) or die('Database Error: ' . mysql_error());
$num = mysqli_num_rows($rs);
if($num >= 1 ){
echo "<div style='margin:10px; color:green; font-weight: bold;'>$num records found!</div>";
echo "<table width='365' border ='0' cellspacing='5' cellpadding='5'>";
echo"<tr><th>RESULTS</th></tr>";
echo "<div class='table-responsive'>";
echo "<table class='table table-hover'>";
while($data = mysqli_fetch_array( $rs )){
?>
<tbody>
<?php
$kuantitas=0;
$kuantitas++;
?>
<form action="aksi.php" method="post" id="formorder">
<tr>
<td><?php echo $data['nama_barang']?></td>
<td><?php echo $data['stok']?></td>
<td><input type="text" name="kuantitas" size="4"></td>
<td><input type="text" name="harga_satuan" id="harga_satuan" size="10"></td>
<td><input type="text" name="ppn" id="ppn" size="3"> %</td>
<td><button type="submit" class="btn btn-success btn-sm" id="add" name="add">ADD</button></td>
</tr>
</form>
<?php }?>
</tbody>
</table>
</div>
<?php
}else{
echo "<tr><th>NO RESULTS</th></tr>";
}
}
?>
the button submit in formorder not working, what wrong with my code???

display jQuery ajax variable in original page after popup window close

I am trying to display data after closing my jQuery window. I know the data is there - I can display it in an alert window after closing my jQuery window. But..., I want that same data displayed in the parent window (for lack of a better term) after the jQuery window is closed. I've been trying to solve this for 3 weeks. Please help!
Lately I've been thinking I need to refresh or reload the parent page? My apologies if "parent page" is the incorrect terminology. What I mean is; the original page from where the jQuery popup window is called.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Dialog - Default functionality</title>
<link rel="stylesheet" href="//whosgotbooks.com/jquery/jquery-ui-1.10.4.custom.css">
<script src="//whosgotbooks.com/jquery/jquery-1.10.2.js"></script>
<script src="//whosgotbooks.com/jquery/jquery-ui-1.10.4.custom.js"></script>
</head>
<body>
<div id="dialog" title="Google Books Search Results" style="display:none;">
<script>
var book_title;
$(function() {
$( "#dialog" ).dialog({
height: 550, width: 450});
$( ".btn" ).click(function(){
//var book_title = $item['volumeInfo']['title'];
$.ajax({
type: "POST",
url: 'book-meta.php',
//dataType: 'json',
//data: { book_title : 'Success!' },
data: { book_title : $("#returnvalues").val() },
success: function(data)
{
$.post("/wp-content/plugins/book-search-google/book-search-google.php", data);
//$(".btn").load("/wp-content/plugins/book-search-google/book-meta.php", data);
alert(data);
//console.log(data);
//$("#dialog").html(data);
},
error: function(errorThrown){
alert('error');
}
});
$( "#dialog" ).dialog( "close" );
});
});
</script>
<strong><p style="font-size: 16px; text-align: center";>Top 10 Results for "<?php echo #$_POST['q']; ?>"</p></strong>
<strong><p style="font-size: 14px; text-align: center";>choose a book to select as your topic</p></strong>
<table style="width:400px">
<col width="325">
<col width="75">
<?php foreach ($data['items'] as $item) { ?>
<?php for($i =1; $i <11; $i++) { ?>
<tr>
<td>
<strong><u><div style="font-size: 14px";><?php printf($item['volumeInfo']['title'])?></u></div></strong>
<strong>Author: </strong><?php printf( $item['volumeInfo']['authors'][0])?><br />
<strong>Published: </strong><?php printf( $item['volumeInfo']['publishedDate']); ?><br />
<strong>Page(s): </strong><?php printf( $item['volumeInfo']['pageCount']); ?><br />
<strong>Publisher: </strong><?php printf( $item['volumeInfo']['publisher']); ?><br />
<strong>Category: </strong><?php printf( strtolower($item['volumeInfo']['printType']).', '.strtolower($item['volumeInfo']['categories'][0])); ?>
<strong>ISBN: </strong><?php printf( $item['volumeInfo']['industryIdentifiers'][0]['identifier']); ?></td>
<td><p><input type="submit" method="post" name="selectbook" value="Select" class="btn" id="returnvalues"/></p>
<img src="<?php printf( rawurldecode($item['volumeInfo']['imageLinks']['smallThumbnail'])); ?>" />
</td>
<tr><td style="width:420px"><p><strong>Description: </strong><?php printf( $item['volumeInfo']['description']); ?><br /></p></td>
</tr>
</tr>
<?php } } }
else {
?>
<p><strong>Sorry, there were no results</strong></p>
<?php }
/* for testing purposes show actual request to API - REMOVE when finished
$apiRequest = $url;
echo '<p>API request: '.$apiRequest.'</p>'; */ ?>
</table>
</div>
</body>
</html>
<?php
else: //show form and allow the user to check for Google Book search results
?>
<p><form id="searchForm" name="searchForm" method="post">
<fieldset id="searchBox">
<label>Search for a Book:</label>
<input class="text" id="q" name="q" type="text" value="Powered by Google" onfocus="this.value=''; this.onfocus=null;" />
<select id="type" name="type" size="1">
<option selected value="all">Book Title</option>
<option value="isbn">Books by ISBN</option>
<option value="lccn">Books by LCCN #</option>
<option value="oclc">Books by OCLC #</option>
</select>
<input class="submit" id="searchForm" name="submit" type="submit" value="Search" />
</fieldset>
</form></p>
<?php
//end submit isset if statement on line 73
endif;
}
Here is my book-meta.php code (most of it is commented out - from trying different things):
if ( isset( $_POST['book_title'] )) {
// session_start();
// header('Location: '.$_SERVER['REQUEST_URI']);
// header('Location: '.$_SERVER['PHP_SELF']);
// $book_title = $_POST['book_title'];
// $_SESSION['book_title'] = $book_title;
// echo $_SESSION['book_title'];
$book_title = $_REQUEST['book_title'];
// $book_title = (isset($_POST['book_title']))?$_POST['book_title'] : 'not yet';
echo $book_title;
echo "Test within IF statement <br>";
}
//$_SESSION['$book_title'] = (isset($_POST['book_title']) ? $_POST['book_title'] : "");
echo "Test outside IF statement <br>";
Here is how I call book-meta.php:
include 'book-meta.php';
//$_SESSION['$book_title'] = (isset($_POST['book_title']) ? $_POST['book_title'] : "");
echo $book_title;//
I can add additional source code if needed. Please help!
If you want to display your data in your html page I suggest you place a div element with the id you want (let's say "displayTest") in this page. Then, when you get your data in the ajax callback function use the following code:
$( "#displayTest" ).append(data);
instead of:
alert(data);
Hope it helps.

Categories

Resources