<script>
$(document).ready(function(){
$("#region").change(function(){
region = $(this).val()
$.ajax({
type:"POST",
data:{"region":region},
url:"get-city.php",
success:function(data){
alert(data);
//$("#city").html(data);
//$("#state").html(data);
}
});
});
});
</script>
<select name="region" id="region" >
<option value="">Select Region</option>
<?php
$sql = mysqli_query($con, "SELECT * FROM `region`");
while($row = mysqli_fetch_array($sql))
{
?>
<option value="<?php echo $row['heading_text']; ?>"><?php echo $row['heading_text']; ?></option>
<?php
}
?>
</select>
<select name="state" id="state">
<option value="">Select Region State</option>
</select>
<select name="city" id="city">
<option value="">Select Region City</option>
</select>
get-city.php
<?php
error_reporting(0);
include('dbase.php');
$region = $_POST['region'];
$sql = "select * from region_data where heading_text='".$region."'";
$results = mysqli_query($con,$sql);
while($rows = mysqli_fetch_assoc($results))
{
$data[] = array(
'state' => $rows['state'],
'city' => $rows['name']
);
}
echo json_encode($data);
?>
In this code I have created simple dropdown one is for region where I change its value by id as you can see in jquery code. Now, As you can see in get-city.php file I have encode data via json_encode function which work fine. But problem is I am not able to show data in state and city drop down in php. My json_encode data look like:
[{"state":"","city":"delhi"},{"state":"","city":"agra"},{"state":"","city":"varanasi"},{"state":"","city":"haridwar"},{"state":"","city":"dharamshala"},{"state":"","city":"srinagar"},{"state":"","city":"mussoorie"},{"state":"","city":"amritsar"},{"state":"","city":"shimla"},{"state":"","city":"kullu manali"},{"state":"","city":"assam"},{"state":"","city":"meghalaya"},{"state":"","city":"arunachal pradesh"},{"state":"","city":"manipur"},{"state":"","city":"nagaland"},{"state":"","city":"J AND K"},{"state":"38","city":"Saharanpur"}]
So, How can I get value in dropdown? Please help me.
Thank You
You'll have to use parseJSON in jQuery to decode the JSON data and then append() the option values to city and state select tags.
<script>
$(document).ready(function(){
$("#region").change(function(){
region = $(this).val()
$.ajax({
type:"POST",
data:{"region":region},
url:"get-city.php",
success:function(data){
var obj = $.parseJSON(data);
$.each(obj, function() {
$("#city").append('<option value="'+this['city']+'">'+this['city']+'</option>');
$("#state").append('<option value="'+this['state']+'">'+this['state']+'</option>');
});
//$("#city").html(data);
//$("#state").html(data);
}
});
});
});
</script>
If you need to get back a JavaScript object from a JSON string, you are looking for JSON.parse().
I did not got exactly how you want to display data, but as far as I understand you are looking for a way to populate the dropdowns, so I will show you only for the city part...for all the other dropdowns the flow is the same.
Assuming you have all the cities in the cities variable after the AJAX call (and after the JSON.parse call if needed):
let cities = [{"state":"","city":"delhi"},{"state":"","city":"agra"},{"state":"","city":"varanasi"},{"state":"","city":"haridwar"},{"state":"","city":"dharamshala"},{"state":"","city":"srinagar"},{"state":"","city":"mussoorie"},{"state":"","city":"amritsar"},{"state":"","city":"shimla"},{"state":"","city":"kullu manali"},{"state":"","city":"assam"},{"state":"","city":"meghalaya"},{"state":"","city":"arunachal pradesh"},{"state":"","city":"manipur"},{"state":"","city":"nagaland"},{"state":"","city":"J AND K"},{"state":"38","city":"Saharanpur"}];
cities.map(function(item, index) {
// let's build an <option> element
const city = jQuery("<option>", {value: item.city, text: item.city})
// let's add the <option> element to the right <select>
jQuery("#city").append(city);
});
this is one of the solution. You can search more for dependent dropdown
use value.city and vvalue.state as you want, or key as option value , its upto you, i just showed how you get values
$.ajax({
url:"get-city.php",
data:{"region":region},
type: "POST",
success: function(data) {
$('select[name="city"]').empty();
$.each( JSON.parse(data), function(key, value) { // or use data without JSON.parse(data)
$('select[name="city"]').append('<option value="'+ value.state +'">'+ value.city +'</option>');
});
}
});
Inside your success section:
success:function(data){
for(let i = 0; i < data.length; i++){
$('select[name="city"]').append('<option value="'+ data[i].city +'">'+ data[i].city +'</option>');
}
}
Related
I am new to Ajax and JavaScript
I have a similar problem with my selects that depends on the other select but don't know where it is going wrong?
This is my Controller code- that passes the member_id to the model and it is supposed to return data back to the view selected.
public function getStates() {
$this->load->model('ReferenceModel');
$this->load->model('DailyModel');
$this->load->model('MembersModel');
$this->load->model('FundsModel');
$postData = array('member_id' => $this->request->getPost('member_id'));
$dataa = $this->FundsModel->getStates($postData);
echo json_encode($dataa);
}```
This is my AJAX Request Code
<script type='text/javascript'>
// baseURL variable
var baseURL= "<?php echo base_url();?>";
$(document).ready(function(){
// City change
$('#member_id').change(function(){
var member_id = $(this).val();
// AJAX request
$.ajax({
url:'<?=base_url()?>Historic/getStates',
method: 'post',
data: {member_id: member_id},
dataType: 'json',
success: function(response){
// Remove options
$('#id').find('Select Member').not(':first').remove();
// Add options
$.each(response,function(index,data){
$('#id').append('<option value="'+dataa['id']+'">'+dataa['fund']+'</option>');
});
}
});
});
});
</script>
Model
public function getStates($postData){
$sql = 'SELECT * FROM vw_funds_summary WHERE member_id =' .$postData['member_id'] ;
$query = $this->db->query($sql);
return $query;
}```
And My HTML Codes
<select id="member_id" name="country" class="form-control">
<option>Select Member</option>
<?php
for ($i=0;$i<$fMembers->num_rows();$i++){
echo "<option value='".$fMembers->row($i)->member_id."'>".$fMembers->row($i)->member_name."</option>";}
?>
</select>
<select class="form-control" id="id">
<option>Select Fund</option>
</select>
What is really wrong with my Code?
I have a view of both the funds and the members, that are giving the results as shown in the attached picture.
Or is there another way to do it without having to use AJAX?
Guys I am very new in Jquery and Json trying, I am trying to create a Dependent Option list with Jquery but it's not working. I am expecting your kind help.
here is my HTML code..
<div class="form-group">
<label for="categoriesId">
Categories</label>
<select class="form-control" id="categoriesId" name="categoriesId">
<option selcted="">Select
Categories</option>
<?php
getCat();
?>
</select>
</div>
and my fetchProductDta.php page code is here
<?php
require_once 'db_connect.php';
if(isset($_POST['cid'])){
$sql = "SELECT product_id, product_name
FROM product WHERE categories_id = '". $cid
."'";
$result = $connect->query($sql);
while($product = $productData->fetch_array()) {
echo "<option value='".$product['product_id']."'>
".$product['product_name']."</option>";
}
}
?>
My Jquery Code is here
$(document).ready(function () {
$("#categoriesId").change(function () {
var cid = $("#categoriesId").val();
$.ajax({
url: 'fetchProductData.php',
method: 'POST',
data: 'cid' + cid
.done(function (product) {
console.log(product);
product = json.parse(product);
product.forEach(function (products) {
$('#product').appned();
});
});
});
In your jquery you have mistakes , first of all you are getting html response from server as Nigel Ren said.So,to get that you don't need to use json.parse .Also i didn't find any id with name product in your html code.and there is no appned function in jquery .So,make below changes in your code to make it worked.
$(document).ready(function () {
$("#categoriesId").change(function () {
var cid = $("#categoriesId").val();
$.ajax({
url: 'fetchProductData.php',
method: 'POST',
data: {cid : cid },
success:function(data){
$("#product").html(data);//here response from server will be display in #product
}
});
});
In my HTML page i have 2 select.
When i change the value into the first select the second select must be change is option value.
Error in console :
Uncaught ReferenceError: Invalid left-hand side in assignment
If i add console.log(result) i see the object in console.
JS code
<script type="text/javascript">
function changeoption() {
$.getJSON('users.php', {nameUser:$('#nameUser').val()}, function(result) {
var select = $('#email');
var options = select.attr('options');
$('option', select).remove();
$.each(result, function(index, array) {
$('option', select) = new Option(array['email']); // the line error
});
});
}
$(document).ready(function() {
changeoption();
$('#userName').change(function() {
changeoption();
});
});
</script>
PHP code
<?php
$result = array();
if(isset($_GET['userName'])) {
$query = $dbh->prepare("SELECT email FROM tbl_users WHERE username = ? ORDER BY userId");
$query->execute(array($_GET['userName']));
$result = $query->fetchAll(PDO::FETCH_ASSOC);
}
echo json_encode($result);
?>
HTML code
<form>
<!-- first select populated by another query inside this page-->
<select name="userName" id="userName">
<option>Name1</option>
<option>Name2</option>
<option>Name3</option>
</select>
<!-- second select -->
<select name="email" id="email">
</select>
</form>
You're trying to assign to a jQuery object. Try creating the new option a different way.
instead of
$('option', select) = new Option(array['email']);
try
$('<option />', {
html: array['email'],
value: array['email']
}).appendTo('#email');
JSFiddle
You might use string append:
$('<option value="new">newOption</option>').appendTo("#email");
$('<option value="'+array['email']'+">'+array['email']+'</option>')
.appendTo("#email");
If you are a more php than jquery guy
you can put the select in a div
<div id='selecthtml'>
<select name="username" id="username">
<option>Name1</option>
<option>Name2</option>
<option>Name3</option>
</select>
</div>
then instead of getjson just use $.get
var url = "users.php?username"+$("#username").val();
$.get( url, function( data ) {
$( "selecthtml" ).html( data );
});
and of course your php users.php should return an html select (not json)
like this
<select name="username" id="username">
<option>New name 1</option>
<option>new name 2</option>
</select>
$('option', select) = new Option(array['email']); // the line error
In this line the $(...) is a function. You may be so used to using jQuery that you have lost sight of this. You cannot perform $(...) = ...; just like you cannot perform alert() = ...;
Change:
$('option', select).remove();
$.each(result, function(index, array) {
$('option', select) = new Option(array['email']); // the line error
});
});
to:
$(select).html('');
$.each(result, function(index, array) {
$(select).append(new Option(array['email']);
}
I have these:
$(document).ready(function() {
getRequestCategories();
$('#requestCategory').change(function() {
getRequestDescriptions( $(this).val() );
});
});
function getRequestCategories() {
$.ajax({
url: 'getCategories.php',
dataType: 'json'
})
.done(function(categoryInfo) {
$(categoryInfo).each(function(i, category) {
$('<option>').val(category.RequestCategoryDisplay).text(category.RequestCategoryDisplay).appendTo( $('#requestCategory') );
})
});
}
function getRequestDescriptions(requestCategory) {
$.ajax({
url: 'getDescriptions.php',
dataType: 'json',
data: { requestCategory: requestCategory }
})
.done(function(descriptionInfo) {
$(descriptionInfo).each(function(i, description) {
$('<option>').val(description.RequestDescriptionDisplay).text(description.RequestDescriptionDisplay).appendTo( $('#description') );
})
});
}
Category
<select name="requestCategory" id="Category" style="width:250px;font-size:10pt;" class="changeable" data-summary="summCategory">
<option value=""></option>
</select>
Description
<select name="description" id="description" style="width:250px;font-size:10pt;" class="changeable" data-summary="summSubCategory">
<option value=""></option>
</select>
How it works currently:
When you select a value from the Category dropdown, all the values associated with your selection are automatically into the description dropdown.
This works fine.
However, we have a new requirement to populate the following hidden form field with user's selection from the description dropdown:
<input name="RequestID" id="RequestID" type="text" width="300" value="" class="changeable" />
In other words, once the description dropdown is populated with values based on selection from Category dropdown, then when a user selects one of the values from the description dropdown, the accompanying value of RequestID should be saved into a hidden form field.
I tried modifying the getDescriptions function but I am not getting the correct values.
Each value I select from the description dropdown gives me same values for RequestID.
Can you please see what I am doing wrong?
Thanks so much in advance.
function getDescriptions(requestCategory) {
$.ajax({
url: 'getDescriptions.php',
dataType: 'json',
data: { requestCategory: requestCategory }
})
.done(function(descriptionInfo) {
// get number of items in array given by php
var Desc_count = descriptionInfo.length;
// loop request descriptions
for (var i = 0; i < Desc_count; i += 1) {
// append an <option> tag to your <select>
$('#description').append('<option value="' + descriptionInfo[i].RequestID + '">' + descriptionInfo[i].RequestDescriptionDisplay + '</option>');
}
// Listen for the value of the <select> to change
$('#description').on('change', function () {
// get the value of the selected option ,the value is the descriptionInfo[i].RequestID
var value = $( "#description option:selected").val();
// Set the value of the hidden fields based on the <select>'s ID choosing the corret array element
$('input[name="RequestID"]').val(value);
});
});
}
Very strange this isnt working.. is your on change event happening in $(document).ready() ?
I try to help:
instad of your $('#description').on('change', function () { event try this:
$(document).ready(function() {
$('#description').change(function() {
$('#RequestID').val($(this).val());
});
});
if this doesnt work try:
$(document).ready(function() {
$('#description').live('change', function() {
$('#RequestID').val($(this).val());
});
});
I'm tring to send and receive parameters with AJAX without any sucess
First I choose AREA and than the CITIES in this area.
Can you please tell me what do I do wrong?
Client side:
<script>
$(document).ready(function(){
$("#first").click(
function(){
var area_id=$("#area_id").val();
$.ajax({
type: "POST",
url: "recs.php",
data: "area_id="+area_id,
cache:false,
success:
function(data){
$("#second").html(data.message);
}
});
return false;
});
});
</script>
<form method="post" action="tosomewhere.php">
<select id="first" name="area_id">
<option value="1">1</option>
<option value="2">2</option>
</select>
<select id="second" name="section"> </select>
</form>
Server Side:
$areaID = $_POST['area_id'];
$second_option = "";
$query2 = mysql_query("SELECT * FROM `cities` WHERE area_id = $areaID ORDER BY id ASC");
while($index = mysql_fetch_array($query2))
{
$id = $index['id'];
$name = $index['name'];
$second_option .= "<option value='$id'>$name</option>";
}
echo $second_option;
exit;
Thank you in advanced
After editing:
I changed the code to something even simpler:
Client side:
<script>
$(document).ready(function(){
$("#first").click(
function(){
var area_id=$("#area_id").val();
$.ajax({
type: "GET",
url: "recs.php",
data: "area_id="+area_id,
cache:false,
success:
function(data){
$("#second").html(data);
}
});
return false;
});
});
</script>
<form method="post" action="tosomewhere.php">
<select id="first" name="area_id">
<option value="1">1</option>
<option value="2">2</option>
</select>
<div id="second"></div>
</form>
Server side:
some text
I'm still not getting the string into
change
$("#second").html(data.message);
to
$("#second").html(data);
<script>
$(document).ready(function(){
$("#first").click(function(){
var area_id=$("#area_id").val();
$("#second").load('tosomewhere.php?area_id=' + area_id);
return false;
});
});
</script>
Changed the jquery a bit. Using GET.
Also the script has changed:
$areaID = (int) $_GET['area_id'];
$second_option = "";
$query2 = mysql_query("SELECT * FROM `cities` WHERE area_id = '$areaID' ORDER BY id ASC");
if (mysql_num_rows($query2) > 0){
while($index = mysql_fetch_array($query2)){
$second_option .= '<option value="'.$index['id'].'">'.$index['name'].'</option>';
}
echo $second_option;
} else {
echo 'No result!';
}
die();
Added (int) before $_GET as a pre-security measurement.
Add this parameter to the ajax function
dataType:'text'
You need to debug code where is actually fault whether you ajax call is actually initialize.
i: check whether value properly fetch in "area_id" js variable
alert(area_id);
ii: if it ok check whether data proper returned from server scriptinog
alert(data); or alert(data.message);
iii: for testing whether you receive data properly, just send out test script.
echo "sample text";
exit;
or try to send data in json format
die('{"message" : "sample text"}');
If all three steps working, then there should be fault in data access script.
If you are not getting output in ajax try using firebug to check what is actually happening in sending request and getting response.