My script is working, the problem is that I am on a page to edit, and was to appear all data
<tr>
<td class="left">Estado</td>
<td>
<select name="estado" id="select2_1" onChange="buscar_cidades()" style="width: 40%;">
<option value="">--</option>
<?php foreach ($arrEstados as $value => $name) {
echo "<option value='{$value}' ".selected($estado,$value).">{$name}</option>";
}?>
</select>
</td>
</tr>
<tr>
<td class="left">Cidade</td>
<td>
<div id="load_cidades">
<select name="cidade" id="select2_2" style="width: 50%;">
<option value="">Select the state</option>
</select>
</div>
</td>
</tr>
function buscar_cidades(){
var estado = $('#select2_1').val();
if(estado){
var url = 'ajax_cidades.php?estado='+estado;
$.get(url, function(dataReturn) {
$('#load_cidades').html(dataReturn);
});
}
}
my file ajax_cidades.php
<?php
require_once('application/config/database.php');
$estado = $_GET['estado'];
$sql = "SELECT * FROM loc_cidade WHERE id_uf = $estado ORDER BY nome";
$res = mysql_query($sql) or die(mysql_error());
$num = mysql_num_rows($res);
for ($i = 0; $i < $num; $i++) {
$dados = mysql_fetch_array($res);
$arrCidades[$dados['id']] = $dados['nome'];
}
?>
<select name="cidade" id="select2_2" style="width: 50%;">
<?php foreach($arrCidades as $value => $nome){
echo "<option value='{$value}'>{$nome}</option>";
}
?>
I already tried everything and could not, function 'selected' checks are equal to brand as 'selected'
print screen
http://oi44.tinypic.com/pu5w6.jpg
I'm not sure why you are having your ajax_cidades.php loop through the same data twice.
<?php
require_once('application/config/database.php');
$estado = $_GET['estado'];
$sql = "SELECT * FROM loc_cidade WHERE id_uf = $estado ORDER BY nome";
$res = mysql_query($sql) or die(mysql_error());
$num = mysql_num_rows($res);
echo '<select name="cidade" id="select2_2" style="width:50%;">';
for ($i = 0; $i < $num; $i++) {
$dados = mysql_fetch_array($res);
echo '<option value="'.$dados['id'].'">'.$dados['nome'].'</option>';
}
echo '</select>';
?>
also, try debugging what the ajax call is returning, by adding
console.log(dataReturn)
to your function after $.get(url, function(dataReturn) {
then check your console to make sure your page is returning the data expected.
Related
I am newbie to JQuery Ajax. May i know how to create a PHP to read the subcategory list depends on the selected maincategory? So far i had create a jQuery AJAX in my asset_add.php
<script src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#main_category').on('change',function(){
var categoryNAME = $(this).val();
if(categoryNAME){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'ac_maincategory='+categoryNAME,
success:function(html){
$('#sub_category').html(html);
}
});
}else{
$('#sub_category').html('<option value="">Select main category first</option>');
}
});
});
</script>
and for HTML,
<tr>
<td valign=top><strong>MAIN CATEGORY</td>
<td><select name="main_category" id="main_category" onchange="this.form.submit()" required>
<?php
$sql = "SELECT * FROM asset_category GROUP BY ac_maincategory" ;
$result = mysqli_query($conn, $sql);
$count=mysqli_num_rows($result);
?>
<option value=""></option>
<?php
if($count > 0)
{
while ($rs = mysqli_fetch_array($result))
{
$ac_maincategory = $rs["ac_maincategory"];
$ac_id = $rs["ac_id"];
?>
<option value="<?=$ac_id?>"><?=$ac_maincategory?></option>
<?php
}
}
?>
</select>
</td>
</tr>
<tr>
<td valign=top><strong>SUB CATEGORY</td>
<td><select id= "sub_category" name="sub_category" autocomplete="off"/ required>
<option value=""></option>
</select>
</tr>
while in my ajaxData.php
<?php
//Include database configuration file
require("config.php");
$conn = dbconnect();
if(isset($_POST["ac_maincategory"]) && !empty($_POST["ac_maincategory"]))
{
$sql = "SELECT * FROM asset_category WHERE ac_maincategory = ".$_POST['ac_maincategory']."" ;
$result = mysqli_query($conn, $sql);
$count=mysqli_num_rows($result);
if($count > 0)
{
echo '<option value="">Select Subcategory</option>';
while ($rs = mysqli_fetch_array($result))
{
$ac_subcategory = $rs["ac_subcategory"];
$ac_id = $rs["ac_id"];
echo '<option value="'.$rs['ac_subcategory'].'">'.$rs['ac_subcategory'].'</option>';
}
}
}
?>
However, when i choose a maincategory in asset_add.php, nothing shown in subcategory. Can anyone tell me which part i do wrong? Thanks for help
Seems you are replacing whole div with $('#sub_category').html(html); so there is only options printed on the view
You can solve it by replacing the line
$('#sub_category').html(html);
to
$('#sub_category').append(html);
Or Just replace this code in ajaxData.php , S
//Include database configuration file
require("config.php");
$conn = dbconnect();
if(empty($_POST["ac_maincategory"])){
die("category is empty");
}
$sql = "SELECT * FROM asset_category WHERE ac_maincategory = " . $_POST['ac_maincategory'];
$result = mysqli_query($conn, $sql);
$count = mysqli_num_rows($result);
if($count > 0)
{
echo '<select id= "sub_category" name="sub_category" autocomplete="off"/ required>';
echo '<option value="">Select Subcategory</option>';
while ($rs = mysqli_fetch_array($result))
{
$ac_subcategory = $rs["ac_subcategory"];
$ac_id = $rs["ac_id"];
echo '<option value="'.$rs['ac_subcategory'].'">'.$rs['ac_subcategory'].'</option>';
}
echo "</select>";
}
this is simple question and should be fixed ASAP. but idk why still not solved yet.
so, please try this
html
remove onchange attribute (remove native js event trigger style with jquery style)
optional:
fix several unclosed tag html
remove unrecomended PHP writing style
into this
<tr>
<td valign="top"><strong>MAIN CATEGORY</strong></td>
<td>
<select name="main_category" id="main_category" required>
<option value=""></option>
<?php
$sql = "SELECT * FROM asset_category GROUP BY ac_maincategory" ;
$result = mysqli_query($conn, $sql);
$count=mysqli_num_rows($result);
if($count > 0)
{
while ($rs = mysqli_fetch_array($result))
{
echo '<option value="'. $rs["ac_id"] .'">'.$rs["ac_maincategory"].'</option>';
}
}
?>
</select>
</td>
</tr>
<tr>
<td valign="top"><strong>SUB CATEGORY</strong></td>
<td>
<select id= "sub_category" name="sub_category" autocomplete="off" required>
<option value="">Select main category first</option>
</select>
</td>
</tr>
jquery
change on('change') with change() // possible dont know when to use on or not
change wrong comparasion on categoryNAME
optional:
change serialize data style using data {} //better for newbie to study
into this
<script>
$(function(){
$('#main-category').change(, function(){
var categoryNAME = $(this).val();
if(categoryNAME != ''){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:{ac_maincategory: categoryNAME},
success:function(html){
$('#sub_category').html(html);
}
});
}else{
$('#sub_category').html('<option value="">Select main category first</option>');
}
})
});
</script>
PHP
reposition default sub-category value out of $count comparasion
into this
<?php
//Include database configuration file
require("config.php");
$conn = dbconnect();
if(isset($_POST["ac_maincategory"]) && !empty($_POST["ac_maincategory"]))
{
$sql = "SELECT * FROM asset_category WHERE ac_maincategory = ".$_POST['ac_maincategory']."" ;
$result = mysqli_query($conn, $sql);
$count=mysqli_num_rows($result);
echo '<option value="">Select Subcategory</option>';
if($count > 0)
{
while ($rs = mysqli_fetch_array($result))
{
$ac_subcategory = $rs["ac_subcategory"];
$ac_id = $rs["ac_id"];
echo '<option value="'.$rs['ac_subcategory'].'">'.$rs['ac_subcategory'].'</option>';
}
}
}
?>
<?php
//.....
//you sql......$result
//.....
if($_POST['ac_maincategory']) {
//this is test
if($_POST['ac_maincategory']=="aaa"){
$result=array("k1"=>"v1","k2"=>"v2");
}else{
$result=array("kk1"=>"v11","kk2"=>"v22");
}
$str = '<option value="">Select Subcategory</option>';
foreach ($result as $k => $v) {
$str .= '<option value="' . $k . '">' . $v . '</option>';
}
echo $str;exit;
}
?>
<html>
<head></head>
<body>
<div>
<select id="main_category">
<option value=""></option>
<option value="aaa">aaa</option>
<option value="bbb">bbb</option>
</select>
</div>
<div>
<select id="sub_category">
<option value=""></option>
</select>
</div>
</body>
</html>
<script src="http://www.w3school.com.cn/jquery/jquery-1.11.1.min.js"></script>
<script>
$("#main_category").change(function () {
var categoryNAME=$(this).val();
$.ajax({
type:'POST',
url:'',
data:{"ac_maincategory":categoryNAME},
success:function(html){
$('#sub_category').html(html);
}
});
})
</script>
test image
https://i.stack.imgur.com/oJLKo.png
https://i.stack.imgur.com/oIw03.png
https://i.stack.imgur.com/vQQrz.png
I have this problem here where when I press the Add button, it should save my selected choices into my table in database.
But when I press it, my table in database did not receive any data.
Did I do something wrong with my code? I need to find a right way to save the data into my designated table.
Any help would be greatly appreciated. Thanks
<?php
include "..\subjects\connect3.php";
//echo "Connection successs";
$query = "SELECT * FROM programmes_list";
$result = mysqli_query($link, $query);
?>
<form name = "form1" action="dropdownindex.php" method="post">
<table>
<tr>
<td>Select Pragramme</td>
<td>
<select id="programmedd" onChange="change_programme()">
<option>select</option>
<?php while($row=mysqli_fetch_array($result)) { ?>
<option value="<?php echo $row["ID"]; ?>"><?php echo $row["programme_name"]; ?></option>
<?php } ?>
</select>
</td>
</tr>
<tr>
<td>Select intake</td>
<td>
<div id="intake">
<select>
<option>Select</option>
</select>
</div>
</td>
</tr>
<tr>
<td>Select Subjects</td>
<td>
<div id="subject">
<select >
<option>Select</option>
</select>
</div>
</td>
</tr>
<input type="submit" value="Add" name="send">
</table>
</form>
<?php
if(isset($_POST['Add'])) {
//print_r($_POST);
$course1 = implode(',',$_POST['programmedd']);
$course2 = implode(',',$_POST['intake']);
$course3 = implode(',',$_POST['subject']);
$db->query("INSERT INTO programmes(programme_registered, intake_registered, subjects_registered)
VALUES (' ".$course1." ',' ".$course2." ', ' ".$course3." ' )");
echo $db->affected_rows;
}
?>
<script type="text/javascript">
function change_programme()
{
var xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","ajax.php?programme="+document.getElementById("programmedd").value,false);
xmlhttp.send(null);
document.getElementById("intake").innerHTML=xmlhttp.responseText;
if(document.getElementById("programmedd").value=="Select"){
document.getElementById("subject").innerHTML="<select><option>Select</option></select>";
}
}
function change_intake()
{
var xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","ajax.php?intake="+document.getElementById("intakedd").value,false);
xmlhttp.send(null);
document.getElementById("subject").innerHTML=xmlhttp.responseText;
}
</script>
//ajax.php
<?php
$dbhost = 'localhost' ;
$username = 'root' ;
$password = '' ;
$db = 'programmes' ;
$link = mysqli_connect("$dbhost", "$username", "$password");
mysqli_select_db($link, $db);
if (isset($_GET["programme"])) {
$programme = $_GET["programme"];
} else {
$programme = "";
}
if (isset($_GET["intake"])) {
$intake = $_GET["intake"];
} else {
$intake = "";
}
if ($programme!="") {
$res=mysqli_query($link, "select * from intakes where intake_no = $programme");
echo "<select id='intakedd' onChange='change_intake()'>";
echo "<option>" ; echo "Select" ; echo "</option>";
while($value = mysqli_fetch_assoc($res)) {
echo "<option value=".$value['ID'].">";
echo $value["intake_list"];
echo "</option>";
}
echo "</select>";
}
if ($intake!="") {
$res=mysqli_query($link, "select * from subject_list where subject_no = $intake");
echo "<select>";
echo "<option>" ; echo "Select" ; echo "</option>";
while($value = mysqli_fetch_assoc($res)) {
echo "<option value=".$value['ID'].">";
echo $value["subjects"];
echo "</option>";
}
echo "</select>";
}
?>
Your error is where you check for button click.
Change to this
If(isset($_POST['send']))
For future purposes and references, When doing the above, include the name attribute from your button and not the value attribute
I have a problem when submit form value from the second select don't show. Can someone explain me what I'm doing wrong because in new in this (maybe is because i use onchange event). Thanks in advance.
index.php
<?php
include("includes/conn.php");
$sql = "SELECT * FROM opstina";
$result = $conn->query($sql);
if($result->num_rows > 0){
$opstineArr = array();
while($row = $result->fetch_assoc()){
$opstineArr[] = $row;
}
}
if(isset($_POST["addNesto"])){
$opstine = $_POST["opstine"];
$ime = $_POST["ime"];
if(isset($opstine)){
if(empty($opstine)){
$error["opstine"] = "izaberite opstinu";
}
}
$naselja = $_POST["naselja"];
if(isset($naselja)){
if(empty($naselja)){
$error["naselja"] = "izaberite naselje";
}
}
if(isset($ime)){
if(empty($ime)){
$error["ime"] = "izaberite ime";
}
}
if(count($error) == 0){
echo 2222;
}
}
include("includes/header.php");
?>
<form action="" method="POST">
<select name="opstine" class="form-control" id="select_id" onchange="getNaselja(this.value)">
<option>..Izaberite Opstinu..</option>
<?php foreach($opstineArr as $key => $opstina): ?>
<option value="<?php echo $opstina['OpstinaID']; ?>" <?php if(isset($opstine) && $opstine==$opstina['OpstinaID']) echo "selected"; ?> ><?php echo $opstina['NazivOpstine']; ?></option>
<?php endforeach; ?>
</select>
<?php if(isset($error["opstine"])) echo $error["opstine"]; ?>
<p>
<select name='naselja' id='naseljeLista' class='form-control' style='margin-top:10px;'>
</select>
<span><?php if(isset($error["naselja"])) echo $error["naselja"]; ?></span>
</p><br>
<input type="text" name="ime" value="<?php if(isset($ime)) echo $ime; ?>" class="form-control col-md-7 col-xs-12"><?php if(isset($error["ime"])) echo $error["ime"]; ?><br><br>
<input type="submit" name="addNesto" class="btn btn-sm btn-success">
</form>
<?php include("includes/footer.php"); ?>
getNaselja.php
global $conn;
include("includes/conn.php");
if(!empty($_POST["opstina_id"])){
$opstinaID = $_POST["opstina_id"];
$sql1 = "SELECT * FROM naselje WHERE OpstinaID=".$opstinaID;
$result1 = $conn->query($sql1);
if($result1->num_rows > 0){
$naseljaArr = array();
while ($one = $result1->fetch_assoc()) {
$naseljaArr[] = $one;
}
}
echo "<option value=''>---Izaberite naselje---</option>";
foreach ($naseljaArr as $key => $value) {
if(isset($_POST["naselja"]) && $value["NaseljeID"]==$_POST["naselja"]){
echo "<option value='".$value['NaseljeID']."' selected='selected' style='display:block;'>".$value['NazivNaselja']."</option>";
}else{
echo "<option value='".$value['NaseljeID']."'>".$value['NazivNaselja']."</option>";
}
}
}
footer.php
<script>
function getNaselja(val){
$.ajax({
type: 'POST',
url: 'getNaselja.php',
data: 'opstina_id='+val,
success: function(data){
$('#naseljeLista').html(data);
console.log(data);
}
});
}
</script>
example of form after submit on index.php
When I choose from first select my data on the console looks like:
<option value=''>---Izaberite naselje---</option>
<option value='4610'>Beška</option>
<option value='4611'>Inđija</option>
<option value='4612'>Jarkovci</option>
<option value='4613'>Krčedin</option>
<option value='4614'>Ljukovo</option>
<option value='4615'>Maradik</option>
<option value='4616'>Novi Karlovci</option>
<option value='4617'>Novi Slankamen</option>
<option value='4618'>Slankamenački Vinogradi</option>
<option value='4619'>Stari Slankamen</option>
<option value='4620'>Čortanovci</option>
I have a dropdown in my form, In which data is being fetch from database, Problem is i want to keep the selected value in the dropdown if page reloads. Any help will be really appreciated.
Here is my code
<select name="ans_type" class="select-form " onChange="checkAnswer(this.value)" style="background-color: #fff !important;width:159px!important;">
<option value="" style="color:#000">Select</option>
<?php
$sql = "select * from (table name)";
$res = mysqli_query($dbhandle,$sql);
$numrows = mysqli_num_rows($res);
if($numrows){
while($obj = mysqli_fetch_object($res)){
if($ansTypeId == $obj->id){
echo '<option value="'.$obj->id.'" style="color:#000" selected>'.($obj->ans_type).'</option>';
}
else{
echo '<option value="'.$obj->id.'" style="color:#000">'.($obj->ans_type).'</option>';
}
}
}
?>
</select>
Try below code.
<select name="ans_type" class="select-form " onChange="checkAnswer(this.value)" style="background-color: #fff !important;width:159px!important;">
<option value="" style="color:#000">Select</option>
<?php
$selectStr = '';
$sql = "select * from (table name)";
$res = mysqli_query($dbhandle,$sql);
$numrows = mysqli_num_rows($res);
if($numrows){
while($obj = mysqli_fetch_object($res)){
$selectStr = ($ansTypeId == $obj->id) ? 'selected' : '';
echo '<option value="'.$obj->id.'" style="color:#000" '.$selectStr.'>'.($obj->ans_type).'</option>';
}
}
?>
</select>
Try this
selected = '';
if($ansTypeId == $obj->id){
$selected = "selected='selected'";
}
echo '<option value="'.$obj->id.'" style="color:#000" $selected>'.
($obj->ans_type).'</option>';
I need a help exporting search query by clicking on export button. I am able to get data from database to the browser. However, when I click on export button, it refreshes the page, and doesnt do anything.
I am new to php and and programming. Any help will be appreciated :)
<?php
include('dbcon.php');
?>
<form id="searchform" action="index.php" method="post">
<table>
<tr>
<td class="searchleftcol"><h3>Service:</h3></td>
<td>
<select id="service" name="service" class="searchoption">
<option value="">-- Select Service Name --</option>
<?php
$resultservice = mysqli_query($con,"Select * from services") ?>
<?php
while ($line = mysqli_fetch_array($resultservice)) {
?>
<option value="<?php echo $line['serviceid'];?>"> <?php echo $line['service'];?> </option>
<?php
}
?>
</select>
</td>
</tr>
<tr>
<td>
<h3>Environment:</h3>
</td>
<td>
<select id="environment" name="environment" class="searchoption">
<option value="">-- Select Environment --</option>
<?php
$resultdomain = mysqli_query($con,"Select * from evn") ?>
<?php
while ($line = mysqli_fetch_array($resultdomain)) {
?>
<option value="<?php echo $line['envid'];?>"> <?php echo $line['env'];?> </option>
<?php
}
?>
</select>
</td>
</tr>
<tr>
<td>
<h3>Status:</h3>
</td>
<td>
<select name="status" class="searchoption">
<option value="Active">Active</option>
<option value="Inactive">Inactive</option>
</select>
</td>
</tr>
</table>
<input type="reset" name="reset">
<input type="submit" name="submit" value="Search">
<input type="submit" name="export" value="Export" />
</ul>
</form>
<?php
if (isset($_POST['submit'])) {
if (empty($_POST['service'])) {
echo "Please select service in dropdown" . "</br>";
}
else {
$service = $_POST['service'];
}
if (empty($_POST['environment'])) {
echo "Please select Environment in dropdown" . "</br>";
}
else {
$env = $_POST['environment'];
}
if ((!empty($service)) && (!empty($env))) {
$sql="SELECT * from servers";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
$mydata = mysqli_query($con,$sql);
$rowcount = mysqli_num_rows($mydata);
// Here I erased code that displays data from MySQL.
if (isset($_POST['export'])) {
if (empty($_POST['service'])) {
echo "Please select service in dropdown" . "</br>";
}
else {
$service = $_POST['service'];
}
if (empty($_POST['environment'])) {
echo "Please select Environment in dropdown" . "</br>";
}
else {
$env = $_POST['environment'];
}
if ((!empty($service)) && (!empty($env))) {
$sql="SELECT * from servers";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
$mydata = mysqli_query($con,$sql);
$rowcount = mysqli_num_rows($mydata);
//Programetically get the Headings of the excel columns
$columns_total = mysqli_num_fields($sql);
for ($i = 0; $i < $columns_total; $i++) {
$heading = mysql_field_name($sql, $i);
$contents .= '"'.$heading.'",';
}
$contents .="\n";
// Get Records from the table
while ($row = mysqli_fetch_array($sql)) {
for ($i = 0; $i < $columns_total; $i++) {
$contents.='"'.$row["$i"].'",';
}
$contents.="\n";
}
// Remove html and php tags etc.
$contents = strip_tags($contents);
//header to make force download the file
Header("Content-Disposition: attachment; filename=ProductsReport".date('d-m-Y').".csv");
print $contents;
}
}
mysqli_close($con);
}
?>}
Thanks,
Ray