Getting the value of dropdownlist in php - javascript

I have the following the html/php code :
<!DOCTYPE html>
<html>
<head>
<title>Voiture</title>
</head>
<body>
Welcome<br>
<form method="post" action="">
Liste de voiture<select name="selected" id="selected">
<?php
$sql = 'select Type from voiture';
$result = $conn->query($sql);
$json = array();
while ($row = $result->fetch_assoc()) {
if(!in_array($row['Type'], $json)){
$json[] = $row['Type'];
echo '<option name = "'.$row['Type'].'">'.$row['Type'].'</option>';
}
}
?>
</select> <br>
<span id="sel" name="sel"></span>
<table border="1">
<tr id="header">
<td>Type</td>
<td>Model</td>
<td>Couleur</td>
<td>Prix</td>
<td>User</td>
<td>Action</td>
</tr>
</table>
<input type="submit" name="submit" hidden>
</form>
<script src="jquery-3.2.1.js"></script>
<script>
$(function(){
$('#selected').on('change',function(){
$('#sel').text(document.getElementById('selected').value);
$.getJSON('phpVoiture.php',function(data){
for (var x = 0 ; x < data.length ; x++){
$('<tr><td>'+data[x]['type']+'</td>'+'<td>'+data[x]['Model']+
'</td><td>'+data[x]['Couleur']+'</td>'+
'<td>'+data[x]['Prix']+'</td>'+'<td></td></tr>').insertAfter($('#header'));
}
});
});
});
</script>
</body>
</html>
And the following php page :
<?php
require_once ('./dbConnect.php');
include ('./Voiture.php');
$sel = $_POST['selected'];
$conn = mysqli_connect(servername, username, password, db ,port);
$query = "select * from voiture where Type = '".sel."'";
$result = mysqli_query($conn, $query);
$json = array();
if(mysqli_num_rows($result)>0){
while($row = mysqli_fetch_assoc($result)){
$json[] = [
'type' => $row['Type'],
'model' => $row['Model'],
'couleur' => $row['Couleur'],
'prix' => $row['Prix']
];
}
}
else{
echo mysqli_num_rows($result);
}
echo json_encode($json);
The problem is that when I select an option in the drop down list nothing happens. I want the query in the second php page to select the cars that have the type that I selected in the drop down list. I tried troubleshooting by echo an alert in both pages that have the value of the selected option, but this step also failed, so I think there is an issue with retrieving the value of the selected option. Any help would be appreciated.

You're not sending the selected value to the server. Add it to the AJAX call:
$.getJSON('phpVoiture.php', { selected: $('#selected').val() }, function(data){
//...
});
Also, your <option> elements don't have values. You used name instead, but that belongs on the <select>. Use value:
echo '<option value="'.$row['Type'].'">'.$row['Type'].'</option>';
Additionally, you're using a GET request instead of a POST request. So you need to look for the value in the $_GET array:
$sel = $_GET['selected'];
You have other typos too, such as an incorrect use of a variable in PHP:
"...".sel."..."
would be:
"...".$sel."..."
Though this brings up a point about SQL injection. You really shouldn't be directly concatenating the variable like that at all. Instead, use prepared statements with query parameters.
It's entirely possible that there continue to be other mistakes in the code I simply haven't spotted yet. You'll want your debugging to include two things:
Looking at your PHP logs for errors.
Using your browser's debugging tools to observe the AJAX request/response.

Related

PHP-jquery-ajax dynamic dependent selection - difficulty

I'm programming a simple form with a dynamic dependent selection. There are two files. One is a php file with html, javascript and php inside, the second is a php file to get data for the second selection and send them back in json format. In the first (and main) file I have the form with two select fields. First field is for province, second is for towns. Data are in a MySQL db, two tables, table_provinces for provinces (103 rows) and table_towns for towns (8000 rows). Normally connect to the db as usual and also link to jquery using a javascript link. First I get provinces options for the first select field, using php to get the values from table_provinces of the db. Then with the javascript " on('change',function(){ here I use ajax...}) " I pass the selected value using ajax to a php file that might extract towns from table_towns and give back (in json format) values to populate the second select field. Javascript gets correctly the selected value from the first selection field (I used an alert to know it), but nothing more happens. So this is the code.
Link to jquery:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
HTML first select field:
<form method="post" action="usemychoice.php">
<select id="province" name="province" color="white">
<option value="" selected>Select a province</option>
This is how I populate the first select field:
<?php
$sql = "SELECT * FROM table_provinces";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "<option value='".$row['prov']."'>".$row['extended_province']."</option>";
}
} else {
echo "Error: ..........";
}
?>
And after closing that field with a /select I have this code to get values for populating with town names the second select field:
<script type="text/javascript">
$(document).ready(function(){
$('#province').on('change',function(){
var provinceID = $(this).val();
if(provinceID){
window.alert("ok you've chosen the province "+provinceID);
$.ajax({
type:'POST',
url:'get_towns.php',
data: 'prov='+provinceID,
success:function(html){
$('#town').html(html);
}
});
}else{
$('#town').html('<option value="">Please select the province first</option>');
}
});
});
</script>
This is the get_town.php code:
<?php
//*****after a require to the connection db routine"
if(!empty($_POST["prov"])) {
$sql = "SELECT * FROM table_towns WHERE prov LIKE '%" .$_POST['prov']."%'";
$result = mysqli_query($conn, $sql);
$json = [];
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$json[$row['prov']] = $row['town'];
} else {
echo "Error: .................";
}
echo json_encode($json);
}
?>
Finally I have the html code :
<select id="town" name="town" color="white">
<option value="" selected>Select province first</option>
At the end of the day, the code has something wrong because I don't get any data back from get_town.php to populate the second select field, and since I didn't see a window.alert that I've put there to check ongoing execution (you don't see it in the code posted here), it seems that is not executed. Any help?
url:'get_towns.php',
Isn't it get_town.php without plural ?
Apparently it seems that the output of get_town.php is JSON
echo json_encode($json);
but in your JS it is directly output to an html element
$('#town').html(html);
Solution:
Either modify get_town.php to send html OR modify the success function in JS to convert received JSON to proper html.
I hope this will help.
UPDATE:
Replace this part of php
while($row = mysqli_fetch_assoc($result)) {
$json[$row['prov']] = $row['town'];
}
with something
echo '<option value="" selected>Select Town</option>';
while($row = mysqli_fetch_assoc($result)) {
echo '<option value="'.$row['town'].'" color="white">'.$row['town'].'</option>';
}
and finally remove the line
echo json_encode($json);

How to display data with radio buttons based on drop down selection?

I'm trying to dynamically generate radio buttons with data in front of them. The data that is to be displayed in front of the radio button is based on a drop down selection, which also displays some data in a text box using javascript.
I tried taking the selected option in a string and use it in the next query, but I know I am doing it wrong.
Database Connection
$db = pg_connect("");
$query = "select account_name,account_code,address1,address2,address3 FROM
customers";
$result = pg_query($db,$query);
//NEW QUERY
$sql1= "select name from conferences";
$result1= pg_query($db, $sql1);
//END
//New Code
<select class="form-control" id="conference" name="conference">
<option value="">Select Conference...</option>
<?php while($rows1 = pg_fetch_assoc($result1)) { ?>
<option value="<?= $rows1['code']; ?>"><?= $rows1['name']; ?></option>
<?php } ?>
</select>
<br>
// END OF NEW CODE
Dropdown to select the data.
<select onchange="ChooseContact(this)" class="form-control"
id="account_name" name="account_name" >
<?php
while($rows= pg_fetch_assoc($result)){
echo '<option value=" '.$rows['address1'].' '.$rows['address2'].'
'.$rows['address3'].''.$rows['account_code'].'">'.$rows['account_name'].'
'.$_POST[$rows['account_code']].'
</option>';
}?>
</select>
Displaying data in the text area based on the selcted value using javascript. (The code works fine till here)
<textarea readonly class="form-control" style="background-color: #F5F5F5;"
id="comment" rows="5" style="width:700px;"value=""placeholder="Address...">
</textarea>
<script>
function ChooseContact(data) {
document.getElementById ("comment").value = data.value;
}
</script>
Displaying data in front of the radio buttons based on the selected option(This code works if I use some random value in the query, but not if I use the selected value 'account_code' from the previous query. I'm using POST GET method to carry the selected value)
<?php
//NEW CODE
$sql = "select order_number, order_date from orders where
customer_account_code = '3000614' and conference_code='DS19-'"; <-Data
gets displayed when put random value like this.
$code = $_GET[$rows['account_code']];
$conf = $_GET[$rows1['conference_code']];
$sql = "select order_number, order_date from orders where
customer_account_code = '$code' and conference_code= '$conf']"; <- But I
want to display the data against the selected value, i.e, the 'account_code'
in the variable $code from the dropdown select
//END
$res = pg_query($db,$sql);
while($value = pg_fetch_assoc($res) ){
echo "<input type='radio' name='answer'
value='".$value['order_number']." ".$value['order_date']."'>"
.$value['order_number'].$value['order_date']." </input><br />";
}
?>
I need to help to find a way to put the selected 'account_code' in a variable and use it in the $sql query.
Please try with this code : (It's work for me)
1- Add this line to your HTML <head>:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js" type="text/javascript"></script>
2- Edit your CODE to this:
Dropdown to select the data:
<select class="form-control" id="account_name" name="account_name">
<option value=""></option>
<?php while($rows = pg_fetch_assoc($result)) { ?>
<option value="<?= $rows['address1'].' '.$rows['address2'].' '.$rows['address3'].'-'.$rows['account_code']; ?>"><?= $rows['account_name']; ?></option>
<? } ?>
</select>
Displaying data in the text area based on the selected value using jQuery:
<textarea readonly class="form-control" style="background-color: #F5F5F5;"
id="comment" rows="5" style="width:700px;" value="" placeholder="Address..."></textarea>
jQuery Code:
<script type="text/javascript">
$('#comment').val($('#account_name').val()); // MAKE A DEFAULT VALUE
(function($) {
$('#account_name').change(function() {
$('#results').html(''); // REMOVE THE OLD RESULTS
var option = $(this).val();
$('#comment').val(option);
// EDIT RADIO WITH AJAX
$.ajax({
type: "POST",
url: "path/test.php",
dataType:'JSON',
data: $('#account_name').serialize()
}).done(function(data) {
for (var i = 0; i < data.length; i++) {
// ADD RADIO TO DIV RESULTS
$('#results').append('<input type="radio" name="answer" value="'+data[i].order_number+'">'+data[i].order_date+'</input><br>');
}
});
});
})(jQuery);
</script>
after that, add this HTML to your page, to show RESULTS FROM AJAX DATA
<!-- RADIOs -->
<div id="results"></div>
3- Create a new file like path/test.php
in this file, use this CODE to return values with JSON :)
<?php
header('Content-type: application/json');
// CONNECT (JUST USE YOUR CUSTOM CONNECTION METHOD & REQUIRE CONFIG FILE IF YOU WANT)
$db = pg_connect("");
$value = explode('-', $_POST['account_name']);
// EXPLODE AND GET LAST NUMBER AFTER < - >
$code = (int) end($value);
$sql = "select order_number, order_date from orders where customer_account_code = '$code'";
$res = pg_query($db, $sql);
// CREATE JSON RESULTS
$is = '';
while($data = pg_fetch_assoc($res)) {
$is .= json_encode($data).', ';
}
// AND GET ALL
echo '['.substr($is, 0, -2).']';
?>

Query a MySQL Database then display retrieved text after form submit

I am attempting to submit a form immediately after a selection is made from a drop-down menu. After the form is submitted I want to send a query to a MySQL database based on the selection from the drop-down and display the retrieved text.
Currently, with what I have below, nothing is displayed, no errors are thrown. The JS submit event handler works but after the page reloads the new text is not displayed.
Any help is greatly appreciated.
The JS for submitting the form:
$(".platformSelectDropDown").change(function() {
$('.platformSelectForm').submit();
});
PHP to run after the form is submitted:
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$platform = $_POST['platformSelectDropDown'];
$description = call_data($tableName, $platform)['Description'];
$application = call_data($tableName, $platform)['Application'];
}
PHP Function for querying and returning the data:
function call_data($tableName, $col, $platformName) {
include('connection.php');
$sql = 'SELECT * FROM $tableName WHERE platform_name = $platformName';
try {
return $db->query($sql);
}
catch (Exception $e) {
echo "Error! " . $e->getMessage() . "<br/>";
return array();
}
}
The Form:
<form class="platformSelectForm" method="post" action="index.php">
<select name="platformSelectDropDown" class="platformSelectDropDown">
...
</select>
<ul class="indent">
<li><?php echo($description); ?></li>
<li><?php echo($application); ?></li>
</ul>
</form>
I believe the code below will do what you want, with some improvements in security and functionality. However, please note that it's not clear to me from your code where $tableName is being set, so I just hard-coded that to be my test table. I intermingled the php and html, because it made it easier for me to work through the problem and I think it will make it easier for you to follow my solution. There's no reason why you can split it back out and functionize the php portions, similar to your original approach, if you prefer. Check it out:
<html>
<body>
<form class="platformSelectForm" id="platformSelectForm" method="post">
<?php
// Get which dropdown option is selected, if any, so can keep selected on page reload
if(!isset($_POST['platformSelectDropDown'])) {
// Not postback, default to first option ("Select One")
$p0Select = ' selected';
$p1Select = '';
$p2Select = '';
} else {
// Is postback
// Set variables for query below
$tableName = 'tbl_platforms_1';
$platformName = $_POST['platformSelectDropDown'];
// set dropdown selection to whatever was select at form submission
if($platformName == 'Platform_1') {
$p1Select = ' selected';
} elseif ($platformName == 'Platform_2') {
$p2Select = ' selected';
} else {
$p0select = ' selected';
}
}
?>
<select name="platformSelectDropDown" class="platformSelectDropDown" onchange="document.getElementById('platformSelectForm').submit()">
<option value="Select_One"<?php echo $p0Select; ?>>Select One</option>
<option value="Platform_1"<?php echo $p1Select; ?>>Platform 1</option>
<option value="Platform_2"<?php echo $p2Select; ?>>Platform 2</option>
</select>
<?php
// If dropdown value is set and does not equal "Select_One"
if(isset($_POST['platformSelectDropDown'])&& $_POST['platformSelectDropDown'] != 'Select_One') {
?>
<ul class="indent">
<?php
try {
// Set database parameters
// Replace these values with appropriate values for your database
// (okay to use an include like you did originally)
$dbhost = 'your_database_host';
$dbname = 'your_database_name';
$dbuser = 'your_database_user';
$dbpass = 'your_database_user_password';
// Create PDO
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Prepare SQL statement and bind parameters
$stmt = $conn->prepare("SELECT * FROM $tableName WHERE platform_name = :platformName");
$stmt->bindValue(':platformName', $platformName, PDO::PARAM_STR);
// Execute statement and return results in an associative array (e.g., field_name -> value)
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Close Connection
$conn = null;
// For each row that was returned, output results
for ($i = 0; $i < count($results); $i++) {
echo '<li>' .$results[$i]['Description'] .'</li>';
echo '<li>' .$results[$i]['Application'] .'</li>';
}
} catch (Exception $e) {
echo '<li>Error! ' .$e->getMessage() . '</li>';
}
?>
</ul>
<?php
};
?>
</form>
</body>
</html>
Code I used to setup test:
DROP TABLE IF EXISTS tbl_platforms_1;
CREATE TABLE IF NOT EXISTS tbl_platforms_1 (
id int AUTO_INCREMENT NOT NULL,
platform_name varchar(20),
Description varchar(20),
Application varchar(20),
PRIMARY KEY (id)
);
INSERT INTO
tbl_platforms_1
(platform_name, Description, Application)
VALUES
('Platform_1', 'Description 1', 'Application 1'),
('Platform_2', 'Description 2', 'Application 2');
If this solves your problem, please remember to mark as answered, so everyone will know you no longer need help (and so I'll get rewarded for the hour I spent coming up with this solution :-). If this doesn't solve your problem, please provide as much detail as possible as to how the current results differ from your desired results and I will try to revise it to fit your needs. Thanks!

Dynamic Dependent Select Box using Jquery and Ajax in PHP

I'm new with coding and I found some really valuable information that could help my register form look better using Ajax.
The problem is that, even though the php files are working fine, I think that the js file is not doing it's job. here:
in the register form there's this:
<?php
include 'php_includes/conexion.php'; (connect to DB users)
include 'php_includes/conexionlugar.php'; (connect to DB states/cities)
?>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="js/jquery.js"></script>
</head>
in the form there's this:
Select State
<select name="departamento" id="departamento">
<option value="">Seleccione Departamento</option>
<?php echo cargar_departamentos();?>
</select>
Select City
<select name="provincia" id="provincia">
<option value="">Seleccione Provincia</option>
</select>
Now, in the conexionlugar.php (tested/working):
<?php
function cargar_departamentos()
{
$connect = mysqli_connect("localhost", "root", "root", "lugar");
$output = '';
$sql = "SELECT * FROM departamentos ORDER BY NOMBRE_DEPA";
$result = mysqli_query($connect, $sql);
while($row = mysqli_fetch_array($result))
{
$output = '<option value="'.$row["IDDEPARTAMENTOS"].'">'.$row["NOMBRE_DEPA"].'</option>';
echo "$output";
}
}
return $output;
?>
in the jquery.js (don't know much about this :()
$(document).ready(function(){
$('#departamento').change(function(){
var IDDEPARTAMENTOS = $(this).val();
$.ajax({
url:'../php_includes/fetch_provincia.php',
type:"POST",
data:{departamentoId:IDDEPARTAMENTOS},
dataType:"text",
success:function(data)
{
$('#provincia').html(data);
}
});
});
});
in the fetch_provincia.php (tested/working)
<?php
$connect = mysqli_connect("localhost", "root", "root", "lugar");
$output ='';
$sql = "SELECT * FROM provincias WHERE departamentos_IDDEPARTAMENTOS = '".$_POST["departamentoId"]."' ORDER BY NOMBRE_PROV";
$result = mysqli_query($connect, $sql);
$output = '<option value="">Seleccione Provincia</option>';
while($row = mysqli_fetch_array($result))
{
$output = '<option value="'.$row["IDPROVINCIAS"].'">'.$row["NOMBRE_PROV"].'</option>';
echo $output;
}
return $output;
?>
Though separately the PHP files are working, the JS file changing departamentoId for IDDEPARTAMENTOS looks like it's not... help me please.
I think I fixed it, deleting the "return" on both php and adding the js to the same page and not calling it through
The data you are sending from php needs to be sent as json. I would actually not do the "formatting" in php. Just return $result:
echo json_encode($result);
then in your js file, just iterate through "data" and create the options:
success:function(data)
{
$.each(data, function(key, val){
console.log("Key: " + key + " val: " + val);
}
}
have a some errors in your code.
First, in "cargar_departamentos", the return it´s out of a function, and in your fetch_provincia.php, not need a return statement.
In your jQuery code, try remove one of both jQuery called in your head, and Change de dataType directive of "text" to HTML.
#gilgameshbk you are calling jquery 2 times in your head
maybe this may cause some conflict.

passing two variable from php to ajax then back to php

I'm new to ajax so I don't know much about ajax syntax. though i am trying here to pass variable from php to ajax and then back to php. I was able able to get it done with one variable when it came to two variables I was confused. I don't even know what to search on google to get an answer my to query. So I will be brief here's my php code. addnewbug.php
<script type="text/javascript" language="javascript" src="./javascripts/jquery.js"></script>
<script type="text/javascript" language="javascript" src="./javascripts/script.js"></script>
</head>
<div class="margin custom">
<body bgcolor="#2e2e2e">
<div style="text-align: center; padding-top: 0px">
<h1 style="color:white;font-size: 50px">Bughound</h1>
</div>
<div class="effect8">
<div class="tableMargin">
<table width="622" class="table">
<tr class="program_row">
<form>
<td width="150" class="td" style="padding-right: 1.9cm">Program</td>
<td width="171" class="td">
<select id="program" class="dropdown">
<option></option>
<?php
require "./db.php";
$sql = "SELECT DISTINCT program_name FROM program";
$result = db($sql);
while ($row = $result->fetch_assoc()) {
$program_name = $row['program_name'];
echo '<option name ="' . $program_name . '">' . $program_name . '</option>';
}
?>
</select>
</td>
<td width="51" class="td">Release</td>
<td width="41" >
<div class="release" id="release">
<select class="release_select" id='release1'>
</select>
</div>
</td>
<td width="103" class="td">Version</td>
<td width="78" class="td">
<div class="version" id="version">
<select class="version_select" id='program_number'>
</select>
</div>
</td>
</form>
</tr>
</table>
This is the original page where I'm trying to make changes in select box using the get passing statement
here's the script.js which I am using to get variable and pass it to another php program..
$(function(){
$("#program").change(function(){
$(".release_select").remove();
$(".version_select").remove();
if($("#program").val() !== "") {
$.get("addnewbug1.php", {program_name: $("#program").val()})
.done(function(data){
$("div.release").after(data);
});
$.get("addnewbug_version.php", {program_name: $("#program").val()})
.done(function(data){
$("div.version").after(data);
});
}
});
$("#program_number").change(function(){
$(".release_select").remove();
if($("#program_number").val() !== "") {
var val2 = $("#program_number").val();
$.get("addnewbug2.php?program_number="+val2, {program_name: $("#program").val()})
.done(function(data){
$("div.release").after(data);
});
}
});
});
The first function is working fine as it takes values from the program and pass it to addnewbug1.php which takes the program name and generate the new select boxes for release and version of it then which is replaced in div-release and division-version(or number)
this is the file where the first function work perfectly - addnewbug1.php
require "./db.php";
echo "<select class='release_select' id='release1'>";
$programname = $_GET['program_name'];
$sql1 = 'SELECT DISTINCT program_release FROM program WHERE program_name="'. $programname .'"';
$result1 = db($sql1);
while ($row1 = $result1->fetch_assoc()) {
$program_release = $row1['program_release'];
echo '<option name ="' . $program_release . '">' . $program_release . '</option>';
}
echo "</select>";
?>
Now I am having error in the second change function of script.js where I need to pass two variables in '$.get' area. Also the .change fucntion for program_number is not working and it won't delete the select box on changing it.
$.get("addnewbug2.php?program_number="+val2, {program_name: $("#program").val()})
and the addnewbug2.php is also the new file which is being used by it is -
require "./db.php";
echo "<select class='release_select' id='release1'><option></option>";
$programname = $_GET['program_name'];
$programnumber = $_GET['program_number'];
$sql1 = 'SELECT DISTINCT program_release FROM program WHERE program_name="'. $programname .'" and program_number=' . $programnumber;
$result1 = db($sql1);
while ($row1 = $result1->fetch_assoc()) {
$program_release = $row1['program_release'];
echo '<option name ="' . $program_release . '">' . $program_release . '</option>';
}
echo "</select>";
?>
I don't know if you get my question or not. Thank you for replying to this question and please reply if require more info.
this is the addidtional db.php code
function db($sql){
//Check for connection variable already set
if(!isset($conn)){
//Database Connectivity - ip, username, password, database name
$conn = new mysqli("i have filled this correctly");
}
//Check Connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = mysqli_query($conn, $sql);
mysqli_close($conn);
return($result);
}
If I get that correctly, your initial problem is to pass more than one variable in AJAX call.
You can construct the URL like this :
var val2 = $("#program_number").val();
var val1 = $("#program").val();
$.get("addnewbug2.php?program_number="+val2+"&program_name="+val1)
json_encode() is perfect for transport php variable with ajax
something like
//your ajax call receiver page -: your_link_for_ajax.php
$output = json_encode(array('type'=>'success','address'=>$address,'table_record'=>$table_record));
die($output);
you can read it like
this code on your html page
$.post('your_link_for_ajax', post_data, function(response){
//load json data from server and output message
if(response.type == 'error')
{
output = '<div class="alert alert-danger">'+response.text+'</div>';
}else{
output = '<div class=" alert alert-success">'+response.address+'</div>';
$('#stateIdContact').html(response.table_record);
}
}, 'json');
Thank you for replying, i solved my problem using AngularJS, which i started reading after posting this question. My main moto behind this question was to populate a (2nd)select box and (3rd)select box using value from other (1st) select box and when the values in newly populate (2nd) select box was done. Then change values (3rd)select box using the (2nd) select box. Vice versa for last point. Apply unique filter to select boxes and without moving to next page.
So here's the code simplified form of Addnewbug.php-
<!DOCTYPE html>
<html >
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src= "https://cdnjs.cloudflare.com/ajax/libs/angular-filter/0.5.4/angular-filter.js"></script>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
<select ng-model="selectProgram">
<option></option>
<option ng-repeat="x in programes | unique: 'prognumber'" name=""{{x.progname}}"">{{ x.progname }}</option>
</select>
<select ng-model="selectNumber">
<option></option>
<option ng-repeat="x in programes | filterBy: ['progname']:selectProgram | filterBy: ['progrelease']:selectRelease | unique: 'prognumber'" name=""{{x.prognumber}}"">{{ x.prognumber }}</option>
</select>
<select ng-model="selectRelease">
<option></option>
<option ng-repeat="x in programes | filterBy: ['progname']:selectProgram | filterBy: ['prognumber']:selectNumber | unique: 'progrelease'" name=""{{x.progrelease}}"">{{ x.progrelease }}</option>
</select>
</div>
<script>
var app = angular.module('myApp', ['angular.filter']);
app.controller('customersCtrl', function($scope, $http) {
$http.get("db/program_db.php")
.success(function (response) {$scope.programes = response.records;});
});
</script>
</body>
</html>
offcourse i used some other stackexchange questions to get it right.
And for the table which is being imported in this code i used this program_db-
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
if(!isset($conn)){
//Database Connectivity - ip, username, password, database name
$conn = new mysqli("*connection parameters*");
}
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = mysqli_query($conn, "SELECT program_name, program_number,program_release FROM program");
$outp = "";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "") {$outp .= ",";}
$outp .= '{"progname":"' . $rs["program_name"] . '",';
$outp .= '"prognumber":"' . $rs["program_number"] . '",';
$outp .= '"progrelease":"'. $rs["program_release"] . '"}';
}
$outp ='{"records":['.$outp.']}';
$conn->close();
echo($outp);
?>
I have same problem as you had in this page: PHP ajax database : how to pass two variables and get data of them in different options? ,i have 2 diffrent php file,one is handling select files,the other handle the database sql,firstly i pass a value which user choosed from first select which updates the second select,and choosing second select should update third select(which is remain empty) i dont know what is my problem(i guess i send value of first ajax to the other php file,and when i get it back to use it for second ajax call,the first value will gone.

Categories

Resources