Getting value from database using jquery on change event - php

I have a list of rooms in a table along with their rent cost. Rooms are listed in a drop down menu, and I want to get rent in "input" field value, "on page load" as well as on "dropdown value change". I wrote following code, but somehow it is not working as expected. Can someone help me with this please?
<?php
define("HOST", "localhost");
define("DB_USER", "root");
define("DB_PASS", "");
define("DB_NAME", "testdb");
$conn = mysqli_connect(HOST, DB_USER, DB_PASS, DB_NAME);
if (!$conn) {
die(mysqli_error());
}
$ajax = false;
$dbValue = 1; //or the default value of your choice - matched to the default selection value of the dropdown
if (isset($_GET['action']) && $_GET['action'] == 'ajax' && isset($_GET['dd'])) {
$dbValue = intval($_GET['dd']);
$ajax = true;
$res = mysqli_query($conn, "SELECT rent FROM `rooms` WHERE roomid = '$dbValue' limit 1");
$dataTable = '';
while ($data = mysqli_fetch_assoc($res)) {
$dataTable = $data['rent'];
}
}
// if ($ajax) return $dataTable;
?>
<html>
<head>
<title>jQuery Validation for select option</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
</head>
<body>
<select class="form-control" id= "roomid" name="roomid" required="">
<?php
$troom_sql = "SELECT roomid FROM rooms WHERE (isactive='y' AND isassigned='n' AND roomid NOT IN (SELECT roomid from roomalloc))";
$troom_rs = mysqli_query($conn, $troom_sql);
while ($troom_mem = mysqli_fetch_assoc($troom_rs)) {
?>
<option value="<?php echo $troom_mem['roomid']; ?>"><?php echo $troom_mem['roomid']; ?></option>
<?php
} ?>
</select>
<input type="text" placeholder="Monthly Rent" class="form-control" id="rent" name="rent" required>
<br>
</body>
<script>
$('#roomid').change(function()
{
var first = $('#roomid').val();
var req = $.get('getDB.php', {dd: first, action: 'ajax'});
req.done(function(data)
{
console.log("asdasd");
$('#rent').val("<?php echo $dataTable; ?>");
});
});
</script>
</html>

Though you've written both PHP and JS in the same file, you still need to return the data from PHP side and handle it in JS.
if ($ajax) return json_encode($dataTable)
from PHP side
dat = JSON.parse(data)
in JS

Crate a JQuery AJAX Function that takes the parameter for POST/GET Request and call that Ajax function on JQuery Event. The Ajax Function Should be like,
function LoadComponentPage( param ){
$.ajax({
type: "POST",
url: "./controller/ajax/component_paginate.php",
data: "page="+param,
dataType: "text",
success: function(resultData){
let section = $('#ComponentsListing');
section.empty();
section.html(resultData);
},
error : function(e){
console.log(e);
}
});
}
and call that function upon event as onclick="LoadComponentPage(param)". you can post process the result of call to show result or error something as shown in example function.

Related

How to check whether a text variable is equal to an Array

My requirement is to check whether a text variable is equal or not to an mysql output array.
The mysql output array I have taken as follows,
$connect = mysqli_connect("localhost", "root", "", "newbooks");
$query = "SELECT book_name FROM takenbooks order by ID DESC";
$result = mysqli_query($connect, $query);
while( $row = mysqli_fetch_assoc( $result)){
$avail_books[] = $row['book_name']; // Inside while loop
}
Now I need to check whether user have entered any book from which included in above array.So I have implemented as below.
$(document).ready(function(){
$('#insert_form').on("submit", function(event){
event.preventDefault();
$('#book_name').val()=$book_required;
if(in_array($book_required,$avail_books))
{
alert("Not Available");
}
else{
$.ajax({
url:"books.php",
method:"POST",
data:$('#insert_form').serialize(),
beforeSend:function(){
$('#insert').val("Inserting");
},
success:function(data){
$('#insert_form')[0].reset();
$('#add_data_Modal').modal('hide');
$('#employee_table').html(data);
}
});
}
}
}
But this is not working. Can someone show where I have messed this?
There can be other ways to accomplish what you want.
For example, use the following query:
SELECT count(*) FROM takenbooks where book_name = ?
But for How to check whether a text variable is equal to an Array and based on your original code, the normal way will be to pass the user input data (I believe is $('#book_name').val()) thru ajax to a PHP file to check whether this data is in the array , then return the result back (or do further processing)
For the HTML
<script
src="https://code.jquery.com/jquery-3.6.0.js"
integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk="
crossorigin="anonymous"></script>
<form id=insert_form>
<input type=text id="book_name">
<input type=submit>
</form>
<script>
$(document).ready(function(){
$('#insert_form').on("submit", function(event){
event.preventDefault();
$.ajax({
type: "POST",
url: 'checkdata.php',
data: {data1: $('#book_name').val()},
success: function(data){
alert(data);
},
error: function(xhr, status, error){
console.error(xhr);
}
});
})
})
</script>
For the PHP (checkdata.php)
<?php
if (isset($_POST["data1"])){
$connect = mysqli_connect("localhost", "root", "", "newbooks");
$query = "SELECT book_name FROM takenbooks order by ID DESC";
$result = mysqli_query($connect, $query);
while( $row = mysqli_fetch_assoc( $result)){
$avail_books[] = $row['book_name']; // Inside while loop
}
if(in_array($_POST["data1"],$avail_books)) {
echo "Not Available";
} else {
// Place insert query here
echo "New Record inserted";
}
}
?>
You can first get the list of books once, then write a Javascript array from which to search for the entered book name. (This may not be practical if the list of books changes quite often, or the list is extremely long.)
<?php
$connect = mysqli_connect("localhost", "root", "", "newbooks");
$query = "SELECT book_name FROM takenbooks order by ID DESC";
$result = mysqli_query($connect, $query);
$avail_books = [];
while( $row = mysqli_fetch_assoc( $result)){
$avail_books[] = $row['book_name']; // Inside while loop
}
?>
<!DOCTYPE html>
<html>
<body>
<form id="insert_form">
Book name: <input type="text" name="book_name">
<input type="submit" value="Check for availability">
</form>
<div id="available"></div>
<script>
const avail_books = <?php json_encode($avail_books); ?>;
document.querySelector('#insert_form').addEventListener(function (evt) {
evt.preventDefault();
let book_name = evt.target.book_name.value;
let not_available = (-1 === avail_books.indexOf(book_name))? 'not': '';
document.querySelector('#available').innerHTML = book_name + " is " + not_available + " available.";
});
</script>
</body>
</html>
PHP, on the server, gets the books and stores the list in a PHP array. And when writing out HTML and Javascript use PHP to write out a Javascript avail_books array containing the book names retrieved from the database.
Now the server can send the client the HTML/Javascript code for rendering. Once loaded in the browser, and if you "View Source", the Javascript code will look something like this:
const avail_books = ["To Kill a Mockingbird", "Animal Farm", "Atlas Shrugged"];
With that the user can check the list of books without having to send a query to the server with every inquiry. It's faster and uses less resources.
It might have some Syntax error but thats the basic concept of what you are trying to achieve. Someones enters text, script searches the database and returns the results.
<html>
<body>
<form action="" method="POST">
<input type="text" name"book" required placeholder="Type the name of the Book" />
<input type="submit" value="Search Book" />
</form>
<div><h2>Results:</h2>
<?php
if(isset($_POST['book'] && !empty($_POST['book'])){
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$connect = new mysqli("localhost", "root", "", "newbooks");
$stmt = $mysqli->prepare("SELECT ID, book_name FROM takenbooks WHERE book_name LIKE ? ORDER BY ID DESC;");
$stmt->bind_param("s", "%" + $_POST['book'] + "%");
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
echo '<p>Book \"' . $row['book_name'] . '\" was found.<br/></p>';
}
}
?>
</div>
</body>
</html>

Dynamic combobox doesn't update

I'm trying to make a combobox that when another combobox is changed it will dynamically update with information from a database. I'm finding a lot of solutions that do not seem to work with what I have and am lost on what to do next.
I've tried simplifying the code to figure out what part does not work, there are so many different versions of the code I tried I just know that some of the one I have right now works and some of it does not.
EDIT: better code (I hope)
Database connexion (root/config/config.php)
<?php
define("DB_HOST", "10.172.16.4");
define("DB_USER", "test2_user");
define("DB_PASS", "password");
define("DB_NAME", "test2");
$dsn = "mysql:host=".DB_HOST.";dbname=".DB_NAME;
$options = [PDO::ATTR_PERSISTENT => true, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION];
try {
$pdo = new PDO($dsn, DB_USER, DB_PASS, $options);
} catch (PDOException $error) {
echo "Connection error: " . $error->getMessage();
die();
}
?>
Header (root/online/templates/header.php)
<!DOCTYPE HTML>
<HTML>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript" src="js/javascript.js"></script>
</head>
<body>
The form (root/online/create.php)
<?php
require_once "templates/header.php";
require_once "../config/config.php";
?>
<form method="post" action="">
<label for="choose_type">Type</label>
<select name="choose_type_modele" id="choose_type" onchange="selectMarque()" required>
<option value="">Select Type</option>
<?php
$sql = "SELECT id, name FROM typeMateriel";
if($stmt = $pdo->prepare($sql)) {
if($stmt->execute()){
$typeMateriel = $stmt->fetchAll();
}
}
foreach($typeMateriel as $foundType){
$typeMateriel_id = $foundType['id'];
$typeMateriel_name = $foundType['name'];
?>
<option value="<?= $typeMateriel_id; ?>"><?= $typeMateriel_name; ?></option>
<?php } ?>
</select>
<label for="choose_marque">Marque</label>
<select name="choose_marque_modele" id="choose_marque" required>
<option value="">Select type first</option>
</select>
</form>
<p id="test"></p>
<?php require_once "templates/footer.php"; ?>
The function (root/online/js/javascript.php)
function selectMarque() {
var typeID = $('#choose_type').val();
var post_id = 'id='+ typeID;
document.getElementById("test").innerHTML = "You Selected " + typeID;
if(typeID){
$.ajax({
type:'POST',
url:'../ajax_marque.php',
data:post_id,
success:function(marque){
$('#choose_marque').html(marque);
}
});
}else{
document.getElementById("choose_marque").innerHTML = '<option value="">Select type first</option>';
}
};
the code for the dynamic stuff (root/online/ajax_marque.php)
<?php
include('../config/config.php');
if($_POST['id']){
$id=$_POST['id'];
if($id===0){
echo "<option>N/A</option>";
} else {
$sql = "SELECT marqueMateriel.id,marqueMateriel.name FROM type_marque, marqueMateriel WHERE marqueMateriel.id=type_marque.marqueMateriel_id AND type_marque.typeMateriel_id= :typeMateriel_id";
if($stmt = $pdo->prepare($sql)) {
$stmt->bindParam(':typeMateriel_id', $id, PDO::PARAM_INT);
if($stmt->execute()){
$marqueMateriel = $stmt->fetchAll();
}
}
echo "<option>Select Marque</option>";
foreach($marqueMateriel as $foundMarque) {
$marqueMateriel_id = $foundMarque['id'];
$marqueMateriel_name = $foundMarque['name'];
echo "<option value='<?php $marqueMateriel_id; ?>'><?php $marqueMateriel_name; ?></option>";
}
}
}
?>
Closing up (root/online/template/Footer.php)
</body>
</html>
The first combo box works, and that's pretty much it. Nothing changes and I'm sure I'm missing something somewhere. I can use the function to alert(typeID) and it does so , but not change the data :/
EDIT : Trying to make more sense ?
The combo box "choose_type_modele" works, it contains everything from the table "typeMateriel". When I select something it does not change the second box "choose_marque_modele". The onchange function is called, as the "test" is modified on selection with the appropriate ID. The code in "ajax_marque.php" works if I copy it inside "create.php" and manually tell it what "$id" is, but it won't do it automatically. I feel the problem is the $.ajax part of the code inside "javascript.js" but I cannot seem to figure out what part is wrong.
Any help would be greatly appreciated.
I don't think if you can add options to a select with html method. You have to create option objects to add select object. To archieve this, you'll change response of your ajax method to JSON object.
var selectMarque = function() {
// Remove current options from matque
$('#choose_marque').find("option").remove();
var typeID = $('#choose_type').val();
var post_id = 'id=' + typeID;
// There will be always value in post_id
// You have to check typeID to be sure if type picked
if (typeID) {
// sample ajax data
var testData = [{
"value": "1",
"text": "Option 1"
},
{
"value": "2",
"text": "Option 2"
},
];
// for each option data in testData
$.each(testData, function(offset, optionData) {
// append an option to select
$('#choose_marque').append($('<option>', {
value: optionData.value,
text: optionData.text
}));
});
} else {
// if empty value picked as type
// add sample option to marque
$('#choose_marque').append($('<option>', {
value: "",
text: "Select Type To Fill"
}));
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="choose_type_modele" id="choose_type" onchange="selectMarque()" required>
<option value="">Select Type</option>
<option value="1">Fill Select</option>
</select>
<select id="choose_marque" required>
<option value="">Select Type To Fill</option>
</select>
I had two errors in my code that made it impossible to work, the url and success parts of the ajax code.
Working code :
$.ajax({
type:'POST',
url:'ajax_marque.php',
data:post_id,
success:function(data){
$('#choose_marque').html(data);
}
});
For some reason I had "marque" instead of data (I might have changed it thinking it was something else ? ) and the url was "../ajax_marque.php". I thought I had to add the url from wherever the javascript.php file was, not from where it was called (create.php).

How to update a field on the form based on a select option

I have a PHP form with the following select list;
<select id ="MatchCaptain" name="MatchCaptain" onchange="findTeleNo(this.value)"
<?php
$MC = $_SESSION["MatchCapt"];
player_load($MC);
?>
>
</select>
I also have a text field ;
Telephone Number: </b> <?php echo $_SESSION["TeleNo"]; ?></p>
The PHP function called by the onchange command is ;
function findTeleNo($MatchCaptain){
$db_handle = mysqli_connect(DB_SERVER, DB_USER, DB_PASS );
$database = "matchmanagementDB";
$db_found = mysqli_select_db($db_handle, $database);
if ($db_found) {
$SQL = "SELECT * FROM `playerstb` ORDER BY `Surname` ASC, `FirstName` ASC";
$result = mysqli_query($db_handle, $SQL);
$ufullName = split_name($MatchCaptain);
while ( $db_field = mysqli_fetch_assoc($result) ) {
$uName = $db_field['FirstName'];
$uName = trim($uName);
$Surname = $db_field['Surname'];
$Surname = trim($Surname);
$fullName = $uName." ".$Surname;
if ($fullName == $ufullName )
{
$_SESSION["TeleNo"] = $db_field['TeleNo'];
include "Match_sort.php";
break;
}
}
}
}
What I am trying to do is when the Match Captains name is changed in the SELECT dropdown list then I want the FUNCTION findTeleNo() to run. Which should then reload the form with the telephone number of the New Match Captain.
However, when I select a new Match Captain the onchange command is ignored.
As a Septuagenarian, just learning this language, I need some help!
Does onchange work in PHP? If not what should I use?
The onchange event is a javascript event, it cannot call your php function directly. You can create a javascript function that will be called when the selects value changes and then this can make an xhr(Ajax) request to a php file which will perform a database query and return what you need it to. You could then update the page with javascript.
PHP is a server side language, you need to use javascript for this.
this is example:
function findTeleNo (value) {
console.log(value);
$.ajax({
url: 'findTeleNo.php',
data: {
c_name: value
},
success: function (response) {
$('#cname').text(response.cname);
$('#teleno').text(response.teleno);
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<select id ="MatchCaptain" name="MatchCaptain" onchange="findTeleNo(this.value)">
<option>choose one</option>
<option value="A1">A1</option>
<option value="B2">B2</option>
<option value="C3">C3</option>
</select>
<div>
<div>
Captain Name is: <span id="cname">empty</span>
<div>
<div>
TeleNo is: <span id="teleno">empty</span>
<div>
and in file findTeleNo.php you print json has cname and teleno.

is there a way to get the value of select tag without submit button or its only possible in jquery

What i want to do is when a user select something in the select tag, the selected value will be save without clicking the submit button. Then i will get what the user select and use it in an if statement. If this is not possible can you show me a simple way to do it in jquery. i try to look for similar questions but they use arrays,while,for that make me confused.
this my current php code. if its not possible may you please show me how to convert this code to jquery.
<form method="post" action="speakers.php">
<label id="sortlabel">Sort By</label>
<select id="sortdrpdwn" name="sortBy">
<option value="none" >None</option>
<option value="name" >Name</option>
<option value="price">Price</option>
<option value="specialization">Specialization</option>
</select>
<input type="submit">
</form>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "srdatabase";
$conn = new mysqli($servername, $username, $password, $dbname);
if($_POST['sortBy'] === 'none')
{
$select_speakers = mysqli_query($conn,"SELECT * FROM speakers");
}
if($_POST['sortBy'] == 'name')
{
$select_speakers = mysqli_query($conn, "SELECT * FROM speakers ORDER BY speaker_fullname ASC");
}
if($_POST['sortBy'] === 'price')
{
$select_speakers = mysqli_query($conn, "SELECT * FROM speakers ORDER BY speaker_paymentcost ASC");
}
if($_POST['sortBy'] === 'specialization')
{
$select_speakers = mysqli_query($conn, "SELECT * FROM speakers ORDER BY speaker_specialization ASC");
echo "wqewqe";
}
?>
i try to do something like this based on sir jay blanchard provide link. I try to post the var selectValue and send it to speakers.php. then echo the selectValue but its not working. Please may you tell me what is wrong?
<script type="text/javascript">
$(document).ready(function()
{
$("#sortdrpdwn").change(function(){
var selectValue = $(this).val();
alert("The text has been changed.");
$.ajax({
method: 'POST',
url: 'speakers.php',
data: {selectValue : selectValue}
})
});
});
</script>
</head>
<body>
<?php
$selectValue = $_POST['selectValue'];
echo $selectValue;
?>
In jQuery you would do this:
$('#sortdrpdwn').change(function(){
var selectValue = $(this).val();
// for testing
console.log(selectValue);
})
Each time the drop down changes selectValue is set to the current value of the option selected.
To use this value with PHP you would then initiate an AJAX request (to a separate PHP script containing your conditions) where PHP would run the query you wish to run, then return the results.
To get started with jQuery/AJAX read this.

Auto complete base on value of dropdown in database

I'm stuck with this problem with in a week. What I have here is dropdown select with ajax posting value to another dropdown but now I need to post into textbox with autocomplete function. What I need is connect my autocomplete query and my ajax so that if I select for example ballpen, all ballpen will recommend in autocomplete. Please Help me with this. I need to finish it.
Here's my code
Ajax.php
<script>
$(document).ready(function(){
$("#tag").autocomplete("autocomplete.php", {
selectFirst: true
});
});
</script>
</head>
<body>
<br/>
Drop1
<?php
$mysqli = new mysqli("localhost", "root", "", "2015");
$combo = $mysqli->query("SELECT * FROM category GROUP BY cat_code ORDER BY id");
$option = '';
while($row = $combo->fetch_assoc())
{
$option .= '<option value = "'.$row['cat_code'].'">'.$row['category'].'</option>';
}
?>
<select id="main" name="main">
<option value="" disabled="disabled" selected="selected">Choose</option>
<?php echo $option; ?>
</select>
Auto Complete <input id="tag">
<script type="text/javascript">
$('#main').change(function(){
$.ajax({
url : 'getajax.php',
data :{mainlist_id : $(this).val()},
dataType:'html',
type:'POST',
success:function(data){
$('#tag').html(data);
}
});
});
</script>
getajax.php
In here I post the value in another dropdown but not I need to post into textbox.
<?php
if (isset($_POST["mainlist_id"])) {
$mysqli = new mysqli("localhost", "root", "", "2015");
$main = $mysqli->real_escape_string($_POST["mainlist_id"]);
$result1 = $mysqli->query("SELECT * FROM code WHERE cat_code='$main' GROUP BY item_code ORDER BY item");
while($row = $result1->fetch_assoc())
{
?>
<option value ="<?php echo $row['item_code'];?>"><?php echo $row['item'];?></option>';
<?php
}
}
?>
autocomplete.php
<?php
//$q=$_GET['q'];
$mysqli = new mysqli("localhost", "root", "", "2015") or die("Database Error");
$auto = $mysqli->real_escape_string($_GET["q"]);
//$main = $mysqli->real_escape_string($_POST["mainlist_id"]); AND cat_code='$main'
$sql = $mysqli->query("SELECT * FROM code WHERE item LIKE '%$auto%' GROUP BY id ORDER BY item" );
if($sql)
{
while($row=mysqli_fetch_array($sql))
{
echo $row['item']."\n";
}
}
?>
//whenever u select the tag field will get focus, and it automatically start searching so u no need to type see the callback focus function with $(this).autocomplete("search", ""); and minlength 0. u have to send the main value and get the response from here too
<script>
$(document).on("keyup", "#tag", function(){
$("#tag").autocomplete({
source: function(request, response) {
$.getJSON("autocomplete_gethere.php", { main: $("#main").val() }, response);
},
minLength:0
}).focus(function() {
$(this).autocomplete("search", "");
});
});
</script>
<script type="text/javascript">
$('#main').change(function(){
$.ajax({
url : 'getajax.php',
data :{mainlist_id : $(this).val()},
dataType:'html',
type:'POST',
success:function(data){
$('#tag').focus(); //please note this, here we're focusing in that input field
}
});
});
</script>
untested, if any question post comment

Categories