<select style="width:300px;" id="FirstDD" name="userListingCategory" onchange="FillSelectTwo(this.options[this.selectedIndex].value)">
<option disabled="disabled">Category...</option>
<?php while($row = $sth2->fetch(PDO::FETCH_ASSOC))
{echo "<option value=". $row['catID'] . ">" .$row['catName']."</option>";}
unset($sth2);
$selectedOptionInCategory = $row['catID'];
?>
</select>
<select style="width:340px;" id="SecDD" name="userListingSCategory">
<option disabled="disabled">Sub-Category...</option>
<?php while($row = $sth3->fetch(PDO::FETCH_ASSOC))
{echo "<option value=". $row['scatID'] . ">" .$row['scatName']."</option>";}
unset($sth3);
?>
When a 'category' is selected like:
I want the subcategories associated with that first category chosen to show up.
I'm running the following SQL:
SELECT scatID, scatName
FROM Category C, SubCategory SC
WHERE C.catID = SC.catID
AND C.catID = '$selectedOptionInCategory'
JS:
function FillSelectTwo(id) { //what is this id for?
$.ajax({
url: 'index.php',
dataType: 'text',
success: function(data) {
$('#SecDD').find('option').remove().end().append(data);
},
error:function(jxhr){
console.log(jxhr.responseText);
}
});
}
Problem I get
When I test this code out, I selected a category like Baby, then the subcategory box clears the first 'disabled' option value, but then its an empty set from there and I can't selected any of the values that the SQL would return upon selecting a category.
What it looks like:
javascript ssems to be fine but i doubt if the ajax call is going out in the first place
see in the firebug or developer tools(for chrome) to confirm that the ajax call is made to index.php
also remove the options in the success callback so if the ajax fails the select remains intact and make an error callback to trace errors
function FillSelectTwo(id) { //what is this id for?
$.ajax({
url: 'index.php',
dataType: 'text',
success: function(data) {
$('#SecDD').find('option').remove().end().append(data);
},
error:function(jxhr){
console.log(jxhr.responseText);
}
});
}
P.S. the is a ' missing at the end of your url may be that is causing the problem
It is pretty easy...
First you need to make a PHP-function that return the subcats. I often make a ajax.php file. In this I have differents functions that being called on in diffs. $_GET.
The PHP viewer for the result.
switch($_GET['ajax'])
{
case 'subcats' :
$sql = [YOUR SQL QUERY];
if(mysql_num_rows($sql)!=0)
{
echo "[";
$i = 0;
while($r = mysql_fetch_array($sql))
{
if($i!=0)
{echo ',';}
echo "['$r[scatID]','$r[ScatName]']";
}
echo ']';
}
break;
}
The jQuery for the ajax request
$.post("ajax.php?ajax=subcats",'id='+$("#FirstDD").val(), function(result){
var print = '';
if(result)
{
for(i = 0;i<result.length; i++)
{
var current = result[i];
print += '<option value="'+ current[0] +'">'+ current[1] +'</option>';
}
$('#SecDD').html(print);
$('#SecDD').removeAttr('disabled');
}
});
It might be some errors (ondemand writings is not my strongest side ^_^), but try to inteplate this to your script. And comment if you meet any errors...
**
EDIT
**
But in your case, when I now understand it. In the subcats options element, add the attr. rel, in wich you write the parent id.
Afterwords, you add this jQuery code:
$('#FirstDD').change(function(){
var thisId = $(this).attr('id');
$('#SecDD option').addAttr('disabled','disabled');
$('#SecDD option[rel="'+thisId+'"]').removeAttr('disabled');
});
Related
I am using Codeigniter 3.1.1. I want City option to display base on the value selected with State option. Actually the City select option does not populate automatically when State option is selected. I tried to link the latest jQuery but still, it doesn't work. Your help is highly appreciated.
MyController.php
class HomeController extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->database();
}
public function index() {
$states = $this->db->get("demo_state")->result();
$this->load->view('myform_view', array('states' => $states ));
}
public function myformAjax($stateID) {
$result = $this->db->where("state_id",$stateID)->get("demo_cities")->result();
echo json_encode($result);} }
View:
<select name="state" id="state" class="form-control" style="width:350px">
<option value="">---Select State---</option>
<?php foreach($states as $key => $value)
{
echo "<option value='".$value->id."'>".$value->name."</option>";
} ?>
</select>
<select name="city" id="city" class="form-control" style="width:350px"></select>
Ajax:
$(document).ready(function() {
$('select[name="state"]').on('change', function() {
var stateID = $(this).val();
if(stateID) {
$.ajax({
url: '/MyController/myformAjax/'+stateID,
type: "POST",
dataType: "json",
success:function(data) {
$('select[name="city"]').empty();
$.each(data, function(key, value) {
$('select[name="city"]').append('<option value="'+ value.id +'">'+ value.name +'</option>');
});
}
});
}else{
$('select[name="city"]').empty();
}
});
});
You've not specified what problem you face when you run your code or what is the output or what is the error, so, we've no way of knowing what the real issue is. However, I'm sharing a working code (an excerpt from my project) of what you want; I've also changed the values according to your needs.
This follows a different approach as AJAX expects HTML to be
returned and that HTML is formed in PHP controller rather than on success in jQuery and then simply added to the desired id.
AJAX
$(document).ready(function() {
$('#state').on('change', function() {
var stateID = $(this).val();
if(stateID) {
$.ajax({
url: '/MyController/myformAjax/'+stateID, // your-controller-path
// sometimes relative path might not work try with base_url() instead or configure your .htaccess properly
type: "POST",
dataType: "html", // expecting html
success:function(data) {
$('#city').empty();
$('#city').html(data); // change innerHTML of id='city'
}
});
}else{
$('#city').empty(); // $('#city').html('');
}
});
});
Controller
public function myformAjax($stateID) {
$cities = $this->db->where("state_id",$stateID)->get("demo_cities")->result(); // get all the cities -- probably want to do this in model
$cityOpt = '<option value="">--Select City--</option>'; // first option -- to prevent first option from automatically selecting when submitting data
foreach($cities as $city)
{
$cityOpt .= '<option value="'.$city->id.'">'.$city->city_name.'</option>'; // concatenate the next value
}
echo $cityOpt;
}
See if it helps you.
I have a <select> with only one option, i want to get the rest of the options from a database using PHP and then populate said <select> with the PHP result using AJAX.
Unfortunately my code is not working, im not surprised as im new to both AJAX and jQuery but i dont get any errors to guide myself through the issue.
The PHP works as expected because its used in another part of the site and i have no issues with it so my error must be in the AJAX (no big surprise here).
Below my HTML:
<select class="custom-select my-1 mr-sm-2" id="producto" name="producto" required>
<option disabled selected value>Elegir...</option>
</select>
Below my AJAX code:
<script type="text/javascript">
$(document).ready(function() {
$("#producto").click(function() {
$.ajax({
url: 'fetch_lista_productos_compra.php',
type: 'get',
success: function(data) {
$("#producto").append(data);
}
});
});
});
</script>
Below my PHP code:
<?php
require $_SERVER['DOCUMENT_ROOT'].'/testground/php/db_key.php';
$conn = mysqli_connect($servername, $username, $password, $dbname);
$sql_query = mysqli_query($conn, "SELECT * FROM productos WHERE disponibilidad = 'disponible'");
while ($row = mysqli_fetch_assoc($sql_query)) {
$titulo = $row['titulo'];
echo <<<EOT
<option value="$titulo">$titulo</option>\n
EOT;
}
?>
As always any kind of help is greatly appreacited and thanks for your time.
IMPORTANT EDIT
<select> has a duplicated id, perhaps i should i have stated this from the start as i know think thats whats causing my issue.
The fact is that in this <form> the selects are created dynamically on user request. They click on Add product and a new select with the products avaiable is created, i know the id/name of said input must have [ ] (id="producto[]") for it to be converted into an array but i dont know how to make the AJAX deal with this dynamically created reapeated selects issue. I apologise for this belated aclaration i realise now it is of the utmost importance.
You have to edit your response from this:
<?php
require $_SERVER['DOCUMENT_ROOT'].'/testground/php/db_key.php';
$conn = mysqli_connect($servername, $username, $password, $dbname);
$sql_query = mysqli_query($conn, "SELECT * FROM productos WHERE disponibilidad = 'disponible'");
while ($row = mysqli_fetch_assoc($sql_query)) {
$titulo = $row['titulo'];
echo <<<EOT
<option value="$titulo">$titulo</option>\n
EOT;
}
?>
To this:
<?php
require $_SERVER['DOCUMENT_ROOT'].'/testground/php/db_key.php';
$conn = mysqli_connect($servername, $username, $password, $dbname);
$sql_query = mysqli_query($conn, "SELECT * FROM productos WHERE disponibilidad = 'disponible'");
$response = '';
while ($row = mysqli_fetch_assoc($sql_query)) {
$titulo = $row['titulo'];
$response .= '<option value="' .$titulo . '">' . $titulo . '</option>'; //Concatenate your response
}
echo $response;
?>
But i suggest to use JSON to get a response and parse it on client side.
You can do this by pushing all values in to response array and use json_encode(). At the end you get straight response from the server with just a values, and append thous values whatever you need on client side.
Update
Also you append data to your existing select options. You can just add thous by editing this:
<script type="text/javascript">
$(document).ready(function() {
$("select#producto").focus(function() { //Change to on Focus event
$.ajax({
url: 'fetch_lista_productos_compra.php',
success: function(data) {
$("select#producto").html(data); //Change all html inside the select tag
}
});
});
});
</script>
Test result:
$('select#options').focus(function(){
alert("Hello this is a select trigger");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="options">
<option value="test">Test</option>
</select>
Please don't construct your html on the server, try to just send the raw data and then construct the html client-side, it's better that way and it leaves room for changing the view later without much coupling.
That said, instead of doing:
while ($row = mysqli_fetch_assoc($sql_query)) {
$titulo = $row['titulo'];
echo <<<EOT
<option value="$titulo">$titulo</option>\n
EOT;
}
just do
$rows = [];
while ($row = mysqli_fetch_assoc($sql_query)) {
$rows[] = $row;
}
//this is your best bet when sending data from PHP to JS,
//it sends the rows as JSON-like string,
//which you'll parse to an array in the client
echo json_encode($rows);
then in the client
$.ajax({
url: 'fetch_lista_productos_compra.php',
type: 'get',
success: (data /*json-like string*/) => {
const dataAsArray = JSON.parse(data);
$.each(dataAsArray, (index, row) => {
//now HERE you construct your html structure, which is so much easier using jQuery
let option = $('<option>');
option.val(row.titulo).text(row.titulo);
$("#producto").append(option);
});
}
});
Regarding your edit about several selects
I don't have access to your server of course so I'm using a mock service that returns JSON. IDs are dynamically generated and all data loading occurs asynchronously after you click on the button.
Try using your url and modify the success function according to your html.
$(document).ready(function() {
$('#add').click(() => {
//how many so far...?
let selectCount = $('select.producto').length;
const select = $('<select class="producto">');
select.attr('id', `producto${selectCount + 1}`);
//then we fetch from the server and populate select
$.ajax({
url: 'https://jsonplaceholder.typicode.com/posts',
type: 'get',
success: function(data) {
data.forEach((d) => {
const option = $('<option>');
option.val(d.id).text(d.title);
select.append(option);
});
}
});
document.body.appendChild(select[0]);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id='add'>Add product</button><br>
<!--<select class="custom-select my-1 mr-sm-2" id="producto" name="producto" required>
<option disabled selected value>Elegir...</option>
</select>-->
HIH
As it turns out the code in the question was actually working properly, the problem was not the code itself but the fact that, as i stated (sadly on a later edit and not right from the start) in the question, there where more than one <select> using the same id, therefore everytime the AJAX was executed the result was appended to the first <select> only, and it was appended over and over again everytime i clicked it, my solution was unifiying both the AJAX that populated the <select> and the jQuery that created the said dynamic <select>'s all in one script thus solving all of my issues at once.
Below my jQuery/AJAX code:
<script type="text/javascript">
$(document).ready(function() {
var max_fields = 10;
var wrapper = $(".input_fields_wrap");
var add_button = $(".add_field_button");
var x = 0;
$(add_button).click(function(e) {
e.preventDefault();
$.ajax({
url: '/testground/php/fetch_lista_productos_compra.php',
type: 'get',
success: function(data) {
if(x < max_fields) {
x++;
var html = '';
html += '<div class="form-group row" id="inputFormRow" style="margin-bottom: 0px;">';
html += '<label class="col-3 col-form-label font-weight-bold">Producto</label>';
html += '<div class="col-7">';
html += '<select class="custom-select my-1 mr-sm-2" id="producto" name="producto[]" required>';
html += '<option disabled selected value>Elegir...</option>';
html += data;
html += '</select>';
html += '</div>';
html += '<div class="col-1 my-auto" style="padding: 0px 0px 0px 0px;">';
html += '<button id="removeRow" type="button" class="btn btn-danger">X</button>';
html += '</div>';
html += '</div>';
$(wrapper).append(html);
}
}
});
});
$(document).on('click', '#removeRow', function () {
$(this).closest('#inputFormRow').remove(); x--;
});
});
</script>
I want to thank everyone that took the time to help me out with this Swati, Serghei Leonenco and Scaramouche, this community is truly amazing.
<script type="text/javascript">
$(document).ready(function() {
$("#producto").change(function() {
$.ajax({
url: 'fetch_lista_productos_compra.php',
type: 'get',
success: function(data) {
console.log(data)
// $("#producto").append(data);
}
});
});
});
</script>`enter code here`
try run this and check in your console that weather you are receiving the data from your php or not.
On my homepage (home.php) I have a first script who take some result of php page (test.php) and display on div #details-menu.
It's the list of "product" table from database.
After when result is selected, I would like to validate it and display on alert.
But it doesn't work... Some idea to help me ?
Here my code :
HOME.PHP (jquery code)
// First display the list of idcat
$(".displaymenu").on('click', function()
{
var idcat=1;
$.ajax({
type: "GET",
url: "test.php",
data: "idcat="+idcat+"",
success: function(msg){
$("#details-menu").html(msg);
}
});
});
// Second validate the choice after selected one product
$('#details-menu').on('click', '.validproduct', function() {
var idproduct=$(this).attr("choice_idproduct");
alert(idproduct);
});
HOME.PHP (html code) :
<div id="details-menu"></div>
TEST.PHP :
<?php
$idcat=$_GET['idcat'];
echo '<select id="choice_idproduct">';
$result = mysql_query("select * from myproduct where idcat='$idcat'");
while ($r_prod = mysql_fetch_array($result_prod))
{
echo '<option value="'.$r_prod['idproduct'].'">'.$r_prod['nameproduct'].'</option>';
}
echo '</select>';
echo '<div class="validproduct">VALIDATE</div>';
?>
You are trying to get an attribute of your div, what is not exists. #choice_idproduct is the child of the div, not an attribute.
Get the value of the select instead.
Try this:
var idproduct=$("#choice_idproduct").val();
i am working in a code igniter .. i am making five rows ..actually i am doing is that the options which are display in the 2nd select box based on the first select box ..
if i dont make five rows with the loop then script is working fine but if i put them in a loop ..selection dont work .. in firebug its give me response false and saying that
localhost/......./controller/get_items/undefined...
i dont know whats wrong in that code
<?php
for ($i = 0; $i < 5; $i++) {
?>
<?php echo form_dropdown('cat_id', $records2, '#', "id='category_".$i."'");?>
<?php echo form_dropdown('item_id', $records3, '#', "id='items_".$i."'"); ?>
<script type="text/javascript">
// <![CDATA[
$(document).ready(function()
{
for (var i= 0; i<5; i++)
{
$('#category_'+ i).change(function()
{
$('#items_'+ i > option").remove();
var category_id = $('#category_'+ i).val();
$.ajax({
type : "POST",
url : "stockInController/get_Items/"+category_id,
success : function(items)
{
$.each(items,function(item_id,item_name)
{
var opt = $('<option />');
opt.val(item_id);
opt.text(item_name);
$('#items_'+ i).append(opt);
});
}
});
});
}
}
As far as i understand your problem here is the solution.
Yor function should look like this
function getCategories(obj)
{
var category_id = obj.id ;
$.ajax({
type : "POST",
url : "stockInController/get_Items/"+category_id,
success : function(data)
{
$('#'+id).html(data);// here you should provide 2nd dropdown id so that it can be replaced
}
});
}
Controller method
function get_Items()
{
$id = $this->uri->segment(3);
$data['result'] = $this->somemodel->getProducts($id);
$this->load->view('options',$data);
}
View
options.php
foreach($result as $row){
?> <option value = "<?php echo $row->item_id?>"><?php echo $row->item_name?></option><?php
}
And on each dropdown of categories you should call this function.
<?php echo form_dropdown('cat_id', $records2, '#', "id='category_".$i."' onclick = "getCategories(this)"");?>
How to code this? when I hover my name It pop outs like a form but I think its not a form
I want exactly the same like this because I want to happen in my page when I hover my name it has a value of id and send it via ajax to the php then the php script queries the id and return its other details then the other details will display like in the image I already have a function and a php code the only I need is how to do like this image
code for js function:
function searchWarriors() {
var id = $("#name").val();
$.ajax({
url: "retrieve_result.php",
type:"GET",
datatype:"json",
data: {id: id},
success: function(data) {
var toAppend = '';
if(typeof data === "object"){
for(var i=0;i<data.length;i++){
var warrior = data[i];
toAppend += '<ul class="ul">';
toAppend += '<li>'+data[i]['loc']+'</li>';
toAppend += '<li>'+data[i]['email']+'</li>';
toAppend += '<li>'+data[i]['sex']+'</li>';
toAppend += '</ul>';
}
$(".ul").remove();
$("#details").append(toAppend);
}
}
});
return false;
}
Code for my PHP:
<?php
header("Content-Type: application/json");
include 'functions/class.php';
$db = new DB();
$result = $db->getDetails($_GET['id']);
$details = array();
foreach($result as $values){
$details[] = $names;
}
echo json_encode($details);
?>
Code for my html to call function
<?php
foreach($result as $id){
//I don't know if this is right
echo'<a id="name" href="myphpcode.php"?id='.$id['user_id'].'>'.$id['name'].'</a>';
}
?>
<div id="details">
</div>
Easiest way to do this is to normally create exactly how you want the pop-up to look in a php script, then use jQuery and call the script with $("#Popup-id").load(script-url.php?getvar=1). The div element will need a high z-index in order to show on top of the screen.