Query new data based on combobox, and display it in new textbox - php

I have a combobox that contains a project number id. Based on the selection of this combobox I want to display the amount of rows in another table containing the same project number id. This value will be appended to the blue box "Number of POs".
My file "new-customer-po.php". I'll display it in parts for simplicity.
<?php
//Query for projectnumber
$query_1 = "SELECT PROJECTNOID, ProjectNumber, ProjectTitle, (SELECT (SELECT
CustomerName FROM tblCustomers WHERE Customer = CUSTOMERID) AS Customer
FROM tblCustomerContacts WHERE CustomerProjectLeadID =
CUSTOMERCONTACTID) AS CustomerProjectLeadID FROM tblProjects ORDER BY
ProjectNumber DESC";
$result_1 = mysqli_query($conn, $query_1);
$options_1 = "";
while($row_1 = mysqli_fetch_array($result_1))
{
$options_1.='<option value="'.$row_1[0].'">'.$row_1[1]." - ".$row_1[2]." - ".$row_1[3].'</option>';
}
?>
further down this page I have the following html
<label>Project Number <b style="color:red;">*</b></label>
<select id="proj" name="projectnum" class="inputvalues" required>
<option disabled selected value>-- Project # - Title - Customer --</option>
<?php echo $options_1; ?>
</select><br>
<div id="currentnumpo">
<label>Number of POs</label><input name="numpos" class="inputvalues" id="reqtxtfield" readonly/><br>
</div>
and after the closing html tag
<script type="text/javascript" >
jQuery(document).ready(function($) {
$("#proj").on('change', function() {
var num = $(this).val();
if(num){
$.ajax ({
type: 'POST',
url: 'getnumberpo.php',
data: { num },
success : function(htmlresponse) {
$('#currentnumpo').html(htmlresponse);
console.log(htmlresponse);
}
});
}
});
});
</script>
My "getnumberpo.php"
<?php
echo $_POST['projectnum'];
if(isset($_POST['projectnum'])){
$sql = "SELECT COUNT(*) FROM tblCustomerPOs WHERE ProjectNum = '".$_POST['projectnum']."'";
$result = $conn->query($sql);
if ($sql) {
while($row = $conn->query($sql)) {
echo '<label>Number of POs</label><input name="numpos" class="inputvalues" id="reqtxtfield" placeholder="';
echo $row[0];
echo '" readonly/><br>';
}
}
$sql = NULL;
}
?>
I'm very new to javascript/ajax so i'm sorry if none of what i'm doing makes sense.
So far when I change the dropdown the whole textbox for "number of po's" dissappears. I've ran the query on "getnumberpo.php" on mysql workbench and it works just fine.
Ex: When I select a project from the dropdown. It will query another table called tblCustomerPOs and check how many rows contain the project number that was selected.
Thanks for the help

If anyone comes across this in the future and wanted the answer...
getnumberpo.php (Server-Side Script)
<?php
require "../inc/dbinfo.inc";
$projectnum =$_POST['projectnum'];
$sql = mysqli_query($conn, "SELECT COUNT(*) AS mycount FROM tblCustomerPOs WHERE ProjectNum = '$projectnum'"); //RESPONSE IS QUERY WITH REAL $PROJECTNUM
$res = mysqli_fetch_object($sql)
$count = $res->mycount;
echo json_encode($count);
exit();
?>
new-customer-po.php (Javascript)
//AUTO UPDATE NUMBER OF POS
$(document).ready(function(){
$('#projectnum').change(function(){
var projectnum = $(this).val();
var data_String;
data_String = 'projectnum='+projectnum;
$.post('getnumberpo.php',data_String,function(data){
var data = jQuery.parseJSON(data);
$('#currentnumpo').val(data)
});
});
});
new-customer-po.php (html)
<label>Project Number <b style="color:red;">*</b></label>
<select id="projectnum" name="projectnum" class="inputvalues" required>
<option disabled selected value>-- Project # - Title</option>
<?php echo $options_1; ?>
</select><br>
<label>Number of Customer POs</label><input type="text" name="currentnumpo" id="currentnumpo" class="inputvalues" readonly/><br>

Related

display Specific data using Ajax and jquery and html select button

hello community i need help on this what i really want to do is to select from database using onchange() function through Ajax.then return the result to the client.i used Ajax to send the information to the server side and but i am having problem return it with the where condition
//this is the html page
<body style="font-family:arial bold; ">
<div style="text-align:left; padding:1%; font-family:Arial bold; color:#cccccc;font-size:40px;"> Select</div>
<select class="form-control" id="color" name="color" >
<option >Please select an option</option>
<option> Red</option>
<option >Yellow</option>
<option >white</option>
<option >Black</option>
<option >Violet</option>
</select>
<br/>
//this is where the output will be displayed with parameter (res);
<div id="dis"></div>
</body>
//this is the script.js
$(function(){
$('#color').on('change', function()
{
var selt= this.value ;
d = $('#color').val();
alert(d);
$.ajax({
url: "ajax-cart.php",
method: "POST",
data: {
request:"select",
selt:selt
}
}).done(function(res) {
$('#dis').val(res) ;
console.log(res);
});
});
//this is ajax cart.php
<?php// START THE SESSION
session_start();// CONFIGURATION
require("db.php");
// PROCESS REQUESTS
switch ($_POST['request']) {
// THIS PART is for the select button
case "select":
require("db.php");
$conn = new mysqli($dbServername, $dbUsername, $dbPassword, $dbName );
$val = $_POST['selt'];
$data = $conn->query("SELECT * FROM `goods` where color = '.$val.' LiMIT 4");
echo Json_encode($data);
break;
this is the console result {"current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null}
#Blessed Media you just missed fetching mysql result, you are just returning query not result.
change your query to
$data = $conn->query("SELECT * FROM goods where color = '".$val."' LiMIT 4");
Add
$result = $data->fetch_array(MYSQLI_ASSOC);
after
$data = $conn->query("SELECT * FROM goods where color = '.$val.' LiMIT 4");
and then
echo json_encode($result);
When sending query to database you don't need to concatenate variables into the query. Just use variables as defined:
Wrong:
$data = $conn->query("SELECT * FROM `goods` where color = '.$val.' LiMIT 4");
Correct:
$data = $conn->query("SELECT * FROM `goods` where color = '$val' LiMIT 4");
After that you will need to produce data from query result. Please check this Q/A for more details.

Getting a value from url and using it in sql query

I'm working on a complex project for a car dealership where I have to create database search based on multiple criteria. The cars in the database are divided into 3 types - let's call them A, B and C. Let's say that the value of A=1, B=2, C=3. The url would look something like index.php?type_id=1 . The working search code so far is as follows.
In index.php :
<script type="text/javascript">
$(document).ready(function(){
$('#car').on('change',function(){
var carID = $(this).val();
if(carID){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'marque_id='+carID,
success:function(html){
$('#model').removeAttr("disabled");
$('#model').html(html);
}
});
}else{
$('#model').attr("disabled");
$('#energy').attr("disabled");
}
});
});
</script>
$type_id = $_GET['type_id];
$query = $db->query("SELECT DISTINCT marque_name,a.marque_id FROM vehicule_marque as a INNER JOIN vehicule as b WHERE b.type_id = '$type_id' AND a.marque_id = b.marque_id order by marque_name");
$rowCount = $query->num_rows;
<div>Select car</div>
<select name="car" id="car" required >
<option value="">Select Car</option>
<?php
if($rowCount > 0){
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['marque_id'].'">'.$row['marque_name'].'</option>';
}
}else{
echo '<option value="">Car not available</option>';
}
?>
</select>
<div>Select car model</div>
<select name="model" id="model" disabled>
<option value=""><!--Select car first--></option>
</select>
In ajaxData.php :
if(isset($_POST["marque_id"]) && !empty($_POST["marque_id"])) {
//Get all state data
$query = $db->query("SELECT DISTINCT a.modele_id, modele_name, a.marque_id FROM vehicule_modele as a INNER JOIN vehicule as b WHERE a.marque_id = ".$_POST['marque_id']." AND b.type_id = '$type_id' AND b.marque_id = a.marque_id AND b.modele_id = a.modele_id ORDER BY modele_name ");
//Count total number of rows
$rowCount = $query->num_rows;
//Display model list
if($rowCount > 0){
echo '<option value="">Select model</option>';
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['modele_id'].'">'.$row['modele_name'].'</option>';
}
}else{
echo '<option value="">Model not available</option>';
}
}
The problem is with taking the type_id value and using it in ajaxData.php query in order to show the model once the customer selected a car brand. In index.php, I GET the value from the url successfully (I tried echoing it and it worked), but then I can't get it to work in the other query - it keeps on showing only "Model not available" option. I tried putting inside the script the $type_id into a new variable, but this didn't work either. I'm not sure what I'm missing. If I remove the type_id condition, everything works perfectly. If anyone has any idea how to fix this, I would appreciate it.
First of all, you need to understand that request to url index.php?type_id=1 and request to url ajaxData.php are different requests and know nothing about each other.
So, if you try to access $_GET['type_id'] in ajaxData.php you will obviously receive nothing, because $_GET is empty in ajaxData.php. If you send request to ajaxData.php?type_id=42 you will get 42 as $_GET['type_id'].
So, you if you want to use some $_GET or $_POST data in ajaxData.php you must send this data explicitly.
It can be either:
url:'ajaxData.php?type_id=' + yourValue,
// access it with $_GET['type_id']
or
data:'marque_id='+carID+'&type_id='+yourValue,
// access it with $_POST['type_id']

How to display the querying 'DB' for get-variable with multiple values?

I am having a problem while displaying the value in the textbox.
I have check boxes that represent for applying job. When a user checks multiple check boxes and clicks the apply button, the id of the check box value is separated with comma and send to applyView.php file using ajax:
Example: applyView.php?id=1,2,3
and the script is
$(document).ready(function(){
$('.job-apply').on('click', function(){
var selected = $('input[name="job[]"]:checked').map(function(i,e){return e.id;}).get();
var res = selected.join(",");
$.ajax({
url: 'php/applyView.php?id='+res,
dataType: 'json',
success: function(data){
if(data.length > 0)
{
var tmp = data[0];
$('#apply-title').attr('value',tmp.apply_title);
}
window.location.href = "apply.php";
}
});
});
And applyView.php file is:
require "dbconnect.php";
$id = $_REQUEST['id'];
$query = mysqli_query($conn, "SELECT `job_title` FROM `job` WHERE `job_id` IN ($id)");
$results = array();
while($row = mysqli_fetch_array($query))
{
$results[] = array(
'apply_title' => $row['job_title'],
);
}
$json = json_encode($results);
echo $json;
Output for the JSON Value is:
[{"apply_title":"Web developer"},{"apply_title":"Software Engineer"},{"apply_title":"Web developer"}]
And apply.php file is:
<form role="form" class="post-resume-form">
<div class="form-group">
<label for="job_title">Job Title</label>
<input type="Text" class="form-control input" id="apply-title" value="" />
</div>
</form>
Now the problem is to display only the value of the id (#apply-title) with separated by comma is it possible.
In the form text box it has to be like this:
"Web Developer","Software Engineer","Web Developer"
Help me out guys!!
If I'm not mistaken, you want to take only the apply title, separated by commas.
Instead of the echo(or beneath it) you can add this code:
$allTitles = "";
foreach($results as $applytitle){
$allTitles = $allTitles . $applytitle["apply_title"] . ",";
}
echo $allTitles;
This should output Web Developer,Software Engineer,Web Developer,.
The last comma(in the output) can be removed with a substring method.
NOTE: I haven't tested this, so it may not work! If you get an error, contact me

On select of combobox value, label has to be displayed dynamically after a select query from database

In a file following code is written which populate the value of combobox :
<select id="company" required="required" class="form-control" value = "select" name="subject_code" placeholder="Select" >
<?php
//Iterating list of subjects available to be filled .
echo "<option> Select </option>";
foreach ($subjects_to_fill as $subject_id => $subject_name) {
# code...
echo "<option value=".$subject_id."> ".$subject_name." </option>";
}
?>
</select>
On selecting a particular item from the combobox, I want to display the faculty_name dynamically from faculty_table on the basis of $subject_id.
table structure:
faculty_table(faculty_id,faculty_name,subject_id)
subject_table(subject_id,subject_name,faculty_id)
You will need to use ajax for this task.
Add a <div> and below script in your current file.
<div id="faculty"></div>
<script type="text/javascript">
function get_faculty()
{
var id = document.getElementById("company").value;
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "get_faculty.php",
data: dataString,
success: function(html)
{
$("#faculty").html(html);
}
});
}
</script>
Now create another get_faculty.php file in same folder which will be called on onchange event of company dropdown.
Write below code in that file
if($_POST['id'])
{
$id=$_POST['id'];
$con=mysqli_connect("localhost","username","pass","dbname");
$sql=mysqli_query($con,"SELECT faculty_name from faculty_table where subject_id = ".$id);
while($row=mysqli_fetch_array($sql))
{
echo $row['faculty_name'];
}
}
Dont forget to write mysqli_connect credentials and query accordingly.

Filter SELECT box from previous SELECT box PHP - SQL Server

I have a couple of SELECT boxes that are pulling from the database, how can I get the option that is selected in SELECT box 1 to filter the SQL in the SELECT box 2?
EG SELECT 1 - Make (Audi, BMW) SELECT 2 - Model (A1,A3, 1 Series, 3 Series)
I want to show that if I pick Audi from SELECT 1 that it will use Audi to fill the WHERE clause in my SQL to filter for the SELECT 2
<label>Manufacturer</label>
<select class="select2_category form-control" data-placeholder="Choose a Category" tabindex="1" id="make" name="make" >
<option value=""></option>
<?php $sqlmake = odbc_exec($cnn, "SELECT DISTINCT Manufacturer FROM lkup.alldata ORDER BY Manufacturer ");
while($manurs = odbc_fetch_array($sqlmake)) {
echo '<option value="'. $manurs['Manufacturer'] .'">'. $manurs['Manufacturer'] .'</option>';
}
?>
</select>
From the above I've been working on this below, which returns no errors but also when you click on the SELECT returns no values in the SELECT.
Where have I gone astray?
My SELECT
<select class="select2_category form-control" data-placeholder="Choose a Category" tabindex="1" id="model" name="model">
<option value=""></option>
</select>
<script>
$(function() {
$('.make').change(function() {
var select = $('.model').empty();
$.get('assets/configs/script.php', {model: $(this).val()}, function(result) {
$.each(result, function(i, item) {
$('<option value="' + item.value + '">' + item.name + '</option>').
appendTo(select);
});
});
});
});
</script>
The script.php
<?php
session_start();
date_default_timezone_set("Europe/London");
error_reporting(0);
include 'config.php'; //my db settings
if (isset($_GET['model'])) {
$model = addslashes($_GET['model']);
$sqlmodel = odbc_exec($cnn, "SELECT DISTINCT ModelName FROM lkup.MyTable WHERE ModelName IS NOT NULL AND Make = $model ORDER BY ModelName ");
$modelrs = array();
while ($row = $sqlmodel->fetch_assoc()) {
$modelrs[] = array(
'ModelName' => $modelrs['ModelName']
);
}
echo json_encode($modelrs);
}?>
If you are familiar with javascript or jQuery you could run another php echo statement to create the other select options with all the possibilities, and then with jQuery hide or show the appropriate options.
$('select[name=first_select]').on('change', function(){
var make = $(this).val();
$.each($('select[name=second_select] option'), function(){
if($(this).prop('class') != make){
$(this).hide();
}
}
});
After a lot of problems with this I found this link that worked a treat. I think my main problem is that I'm using PHP & MS SQL Server, which makes life difficult.
This I found as my solution

Categories