AJAX not triggering preset function using PDO to retrieve from database - javascript

Having this part in an HTML form, working in PHP for server-side backend. Need the user to select country and based on the country the city list is refined to that particular country cities only. AJAX is refreshing and passing the variables but the PHP function is not triggering:
// PHP part
$action = "all";
if (isset($_POST['action'])) {
$action = $_POST['action'];
}
if (isset($_GET['action'])) {
$action = $_GET['action'];
}
<label class="form-text" id="further-details-labels" for="country">Country:</label>
<select onchange="getCountry(this.value)" class="form-control country" name="country" id="country">
<?php
echo "<option value=\"\">Please select Country</option>";
foreach ($model->getCountry() AS $countries => $country) {
echo "<option value={$country['country_code']}>{$country['country_name']}</option>";
}
?>
</select>
<label class="form-text" id="further-details-labels" for="city">City:</label>
<select class="form-control" name="city" id="further-details-input">
<option value="">Please select City</option>
<?php
switch ($action) {
case "all":
$model = new model();
foreach ($model->getCity() AS $cities => $city) {
echo "<option value={$city['city_code']}>{$city['city_name']}</option>";
}
break;
case 'country':
$country = $_POST['country'];
$model = new model();
foreach ($model->getCityByCountry($country) as $cities => $city) {
echo "<option value={$city['city_code']}>{$city['city_name']}</option>";
}
break;// to continue switch statement and add ajax calls
}
?>
</select>
AJAX
<script type="text/javascript">
// TODO fetching script for onchange
function getCountry(country_code) {
if (window.XMLHttpRequest) {
var xhr = new XMLHttpRequest();
} else {
var xhr = new ActiveObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200) {
var country = {"country": country_code};
console.log(country);
var test = document.getElementById("test");
// test.innerHTML=this.responseText;
}
};
xhr.open("POST","details.php", true);
xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");
xhr.send("action=country&country="+country);
};
</script>
Any suggestion as to how to connect them to make the select options change based on the function triggered please?

You need to check $action before printing the rest of the form, not inside the form. If it's all you print the whole form, if it's country you just print the country options.
<?php
switch ($action) {
case "all":
?>
<label class="form-text" id="further-details-labels" for="country">Country:</label>
<select onchange="getCountry(this.value)" class="form-control country" name="country" id="country">
<?php
echo "<option value=\"\">Please select Country</option>";
foreach ($model->getCountry() AS $countries => $country) {
echo "<option value={$country['country_code']}>{$country['country_name']}</option>";
}
?>
</select>
<label class="form-text" id="further-details-labels" for="city">City:</label>
<select class="form-control" name="city" id="further-details-input">
<option value="">Please select City</option>
<?php
$model = new model();
foreach ($model->getCity() AS $cities => $city) {
echo "<option value={$city['city_code']}>{$city['city_name']}</option>";
}
?>
</select>
<?php
break;
case 'country':
$country = $_POST['country'];
$model = new model();
foreach ($model->getCityByCountry($country) as $cities => $city) {
echo "<option value={$city['city_code']}>{$city['city_name']}</option>";
}
break;// to continue switch statement and add ajax calls
}
Then in the AJAX code, the callback function should do:
document.querySelector("select[name=city]").innerHTML = this.responseText;

Related

Dynamic drop down using single table in codeIgniter

Table
Here when I select Category 1 from drop down I should get district names which comes under Category 1 and for Category 2 I should get districts of Category 2 and so on....
As of now in my code i'm pulling out all district names from my district table master by using district codes. But I should get district names based on category selection.
View:
<select class="form-control" name="category" id='cat_id'>
<?php
foreach($query1 as $row)
{
echo '<option value="'.$row->category.'">'.$row->category.'</option>';
}
?>
</select>
<select name="placename" id="placename">
<?php
foreach($query2 as $row)
{
echo '<option value="'.$row->district_name.'">'.$row-
>district_name.'</option>';
}
?>
</select>
Model:
function viewcatplace()
{
$this->db->select("district.district_name");
$this->db->from('district');
$this->db->join('jc_place_master', 'district.district_code =
jc_place_master.district');
$query = $this->db->get();
return $query->result();
}
Controller:
public function viewcatplace()
{
$this->load->model('JcMeetingExpense_model');
$data['query1'] = $this->JcMeetingExpense_model->viewcatprice();
$data['query2'] = $this->JcMeetingExpense_model->viewcatplace();
$this->load->view('JcMeetingExpense/place_view',$data);
}
You can use this demo for your solution : https://www.codexworld.com/dynamic-dependent-dropdown-codeigniter-jquery-ajax/
It can be only done by ajax:
In controller:
public function index()
{
$web = array();
$web['title'] = 'Select tool';
$web['content'] = 'web/category_index';
// $web['data'] = $this->Common_model->get_all('category','*','','');
$web['data'] = $this->db->query('SELECT DISTINCT category FROM category')->result();
$this->load->view('web_template', $web);
}
Load the category data in select option:
<select class="form-control" id="select_category">
<option value="" disabled selected>Select category</option>
<?php if (isset($data) && !empty($data)) : ?>
<?php foreach ($data as $key => $value) : ?>
<option value="<?php echo $value->category; ?>"><?php echo $value->category; ?></option>
<?php endforeach; ?>
<?php endif; ?>
</select>
<select class="form-control" id="append_district"></select>
Using jquery change event get the data using ajax call:
<script type="text/javascript">
$(document).on('change',"#select_category",function (e) {
var optVal= $("#select_category option:selected").val();
if (optVal) {
$.ajax({
type: "post",
url: "getCategoryDetails",
cache: false,
data: {'category' : optVal},
success: function(json){
try {
var obj = jQuery.parseJSON(json);
$('#append_district').empty();
var append_data = '';
if (obj.length > 0) {
$.each(obj, function( index, value ) {
append_data += '<option value="'+value.district+'">'+value.district+'</option>'
});
$('#append_district').append(append_data);
}
} catch(e) {
console.log('Exception while request..');
}
},
error: function(){
console.log('Error while request..');
}
});
}
});
</script>
The data can be get by JSON format.In controller add this method:
public function getCategoryDetails() {
$category = $_POST['category'];
$categoryData = $this->db->query('SELECT district FROM category where category="'.$category.'"')->result();
echo json_encode ($categoryData) ;
}

Fetching data using onChange jquery ajax issue

here in my code i am trying to fetch and display the data after selecting a option from the dropdown using onChange, fetching data from a PHP file and via ajax displaying it in textarea in same select.php file but unfortunately it is not working out for me am quit confused were i made a mistake, please help me out on this.
select.php
<head>
<script type="text/javascript">
$(document).ready(function() {
$("#channel").change(function(){
$.post("ajax.php", { channel: $(this).val() })
.success(function(data) {
$(".result").html(data);
});
});
});
</script>
</head>
<div class="col-sm-6 form-group">
<select class="chosen-select form-control" id = 'channel' name="ProductCategoryID" value="<?php echo set_value('ProductCategoryID'); ?>" required>
<option>Select Item code</option>
<?php
foreach($itemlist as $row)
{
echo '<option value="1234">'.$row->ItemCode.'</option>';
}
?>
</select>
</div>
<div class="col-sm-12 form-group result"></div>
ajax.php
<?php
define('HOST','localhost');
define('USER','***');
define('PASS','***');
define('DB','***');
$response = array();
$conn = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
//get value from page
$channel = $_POST['channel'];
$query = "SELECT * FROM gst_itemmaster where ItemCode = '$channel' ";
$result = mysqli_query($conn,$query);
$msg = '';
while($row = mysqli_fetch_array($result)) {
$msg = $msg. '<textarea type="text" class="form-control" name="Description"></textarea>'.$row['ItemDescription'].'</textarea>';
}
echo $msg;
while($row = mysql_fetch_array($result)) {
$msg = $msg. '<textarea type="text" class="form-control" name="Description"></textarea>'.$row['ItemDescription'].'</textarea>';
}
Try using:
while($row = mysqli_fetch_array($result)) {
$msg = $msg. '<textarea type="text" class="form-control" name="Description"></textarea>'.$row['ItemDescription'].'</textarea>';
}
May be it would help
replace,
$.post("ajax.php", { channel: $(this).val() })
with
$.post("ajax.php", { 'channel': $(this).val() })
$.post("ajax.php", { channel: $(this).val() },function(data) {
$(".result").html(data);
});
Please remove .success(function(data){ }) from the code and it will work :)
Try to initiate $msg first and use mysqli module.
define('HOST','localhost');
define('USER','***');
define('PASS','***');
define('DB','***');
$response = array();
$conn = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
//get value from page
$channel = $_POST['channel'];
$query = "SELECT * FROM gst_itemmaster where ItemCode =$channel";
$result = mysqli_query($conn,$query);
$msg = '';
while($row = mysqli_fetch_array($result)) {
$msg = $msg. '<textarea type="text" class="form-control" name="Description"></textarea>'.$row['ItemDescription'].'</textarea>';
}
echo $msg;
UPDATE
Update your post request with:
$.post("ajax.php",
{ channel: $(this).val() },
function(data) {
$(".result").html(data);
}
);
OR
$.post("ajax.php",
{ channel: $(this).val() },
successCallback
);
function successCallback(data){
//process data..
}
see https://api.jquery.com/jquery.post

Sending two values to PHP via ajax POST to query SQL db

I'm trying to send two values from a form to another PHP using ajax post method. One value is the value that's already entered in an input box, and the other is a value that is being typed into another input box. It acts like a search box. I tried executing the SQL query in my SQL workbench and it returns the value properly. What am I doing wrong in my code?
function searchq6(){
var searchstate = $("input[name='region']").val();
var searchTxt = $("input[name='suburb']").val();
$.post("search-suburb.php", {searchVal: searchTxt, st:searchstate},function(sbb){
$("#sbb").html(sbb);
//searchq7();
});
}
This is the input box where I search and get the value from:
<input type="text" name="region" list="state" value="<?php echo $region; ?>" placeholder="Select State" id="output">
Suburb:
<input type="text" name="suburb" list="sbb" value="<?php echo $suburb; ?>" onkeyup="searchq6()" id="output">
<datalist id="sbb" name="taskoption6" >
<option> </option>
</datalist>
This is the search-suburb.php file:
$output = '' ;
if (isset($_POST['searchVal'])){
$searchq = $_POST['searchVal'];
$st = $_POST['st'];
$query = mysqli_query($link, "SELECT DISTINCT title FROM `wp_locations` WHERE state="'.$st.'" AND `title` LIKE '%".$searchq."%' ")or die("Could not search!");
$count = mysqli_num_rows($query);
if($count == 0){
$output = '<option>No results!</option>';
}else{
while($row = mysqli_fetch_array($query)){
$suburb = $row['title'];
?>
<option value="<?php echo $suburb; ?>"><?php echo $suburb; ?> </option>
<?php
} // while
} // else
} // main if
<input type="text" name="region" list="state" value="<?=(isset($_POST['region'])?$_POST['region']:'');?>" placeholder="Select State" id="output">
Suburb:
<input type="text" name="suburb" onkeyup="searchq6()" list="sbb" value="<?=(isset($_POST['suburb'])?$_POST['suburb']:'');?>" onkeyup="searchq6()" id="output">
<datalist id="sbb" name="taskoption6"></datalist>
Javascript:
function searchq6(){
var searchstate = $("input[name='region']").val();
var searchTxt = $("input[name='suburb']").val();
$.post("search-suburb.php", {searchVal: searchTxt, st:searchstate},function(sbb){
var decode = jQuery.parseJSON(sbb); // parse the json returned array
var str = ""; // initialize a stringbuilder
$.each(decode, function (x, y) {
str+="<option value='" + y.title +"'>";
});
$("#sbb").html(str);
}); // end of post
}// end of searchq6 function
Php:
$output = '' ;
if (isset($_POST['searchVal'])){
$searchq = $_POST['searchVal'];
$st = $_POST['st'];
$query = mysqli_query($link, "SELECT DISTINCT title FROM `wp_locations` WHERE state='{$st}' AND `title` LIKE '%{$searchq}%' ")or die("Could not search!");
$count = mysqli_num_rows($query);
if($count == 0){
$output = '<option>No results!</option>';
} else{
$data = array();
while($row = mysqli_fetch_array($query))
$data[] = $row;
echo json_encode($data);
}
} // main if
Got the answer from small snippets gathered through the comments
Changed the query to:
$query = mysqli_query($link, "SELECT DISTINCT title FROM `wp_locations` WHERE state='".$st."' AND `title` LIKE '%".$searchq."%' LIMIT 10")or die("Could not search!");
And the ajax to:
function searchq6(){
var searchstate = $("input[name='region']").val();
var searchTxt = $("input[name='suburb']").val();
$.post("search-suburb.php", {searchVal: searchTxt, st:searchstate})
.done(function(sbb) {
$("#sbb").html(sbb);
});
//searchq7();
}
Thanks for all the comments guys

JQuery Dynamic Option Select Issue

This is the continution of this Question
Here is the Code for Dynamic JQuery Option Select Generator.
First i will choose the Country, which i didn't include the code, it will return the CountryID which is passed to the controller, then RegionID, then CityID. IT works well until generating the CityID Option select Menu, while i move to the AreaID it didn't work.
What i am missing and how can i fix that ?
I can't able to generate the Menu after the third Second One.
Here is the HTML :
<div id='result' name="result">
<select id="name">
<option value="" disabled>Please select above</option>
</select>
</div>
<div id='resulta' name="resulta">
<select id="name">
<option value="" disabled>Please select above</option>
</select>
</div>
<div id='resultb' name="resultb">
<select id="name">
<option value="" disabled>Please select above</option>
</select>
Here is my Script :
<script>
var ab = $.noConflict();
ab(document).ready(function() {
ab(document).on("change", "#CountryID", function() {
var CountryID = ab("#CountryID").val();
ab.post("globalregiongenerator", {
CountryID: CountryID
},
function(data) {
ab("#result").html(data);
});
});
});
</script>
<script>
var ac = $.noConflict();
ac(document).ready(function() {
ac(document).on("change", "#RegionName", function() {
var RegionName = ac("#RegionName").val();
ac.post("globalcitygenerator", {
RegionName: RegionName
},
function(data) {
ac("#resulta").html(data);
});
});
});
</script>
<script>
var ad = $.noConflict();
ad(document).ready(function() {
ad(document).on("change", "#CityName", function() {
var CityName = ad("#CityName").val();
ad.post("globalareagenerator", {
CityName: CityName
},
function(data) {
ad("#resultb").html(data);
});
});
});
</script>
And here is the Server Side :
public function globalregiongenerator()
{
$CountryID = Input::get('CountryID');
$result = DB::select("SELECT * FROM region where CountryID =$CountryID");
echo "<select id='RegionName' name='RegionName'> <option value='' id=''>Select the Area</option>";
foreach ($result as $value)
{
echo "<option value=".$value->RegionID.">".$value->RegionName."</option>";
}
echo "</select>";
}
public function globalcitygenerator()
{
$RegionID = Input::get('RegionName');
$result = DB::select("SELECT * FROM city where RegionID =$RegionID");
echo "<select id='CityName' name='CityName'> <option value='' id=''>Select the Area</option>";
foreach ($result as $value)
{
echo "<option value=".$value->CityID.">".$value->CityName."</option>";
}
echo "</select>";
}
public function globalareagenerator()
{
$CityID = Input::get('CityName');
$result = DB::select("SELECT * FROM area where CityID =$CityID");
echo "<select id='CityName' name='CityName'> <option value='' id=''>Select the Area</option>";
foreach ($result as $value)
{
echo "<option value=".$value->CityID.">".$value->CityName."</option>";
}
echo "</select>";
}
Note :
Uncaught TypeError: undefined is not a function
This is the error i got in console
Change
echo "<option value=".$value->CityID.">".$value->CityName."</option>";
to
echo "<option value='".$value->CityID."'>".$value->CityName."</option>";
Same with other echos. You're generating
<option value=united states>United States</option>
but it needs to be
<option value='united states'>United States</option>
Update:
Change them to
echo "<option value=\"".$value->CityID."\">".$value->CityName."</option>";

How to pass the value dropdownlist without using form

I have two sets of option value. I created another dropdown that if I choose r it echo <option value $row['nego'] > or n echo <option value $row['rfq'] >. What I want is to pass the value of dropdown without using form. If it possible to do that?
<script>
function showUser(str) {
var $txtHint = $('#txtHint');
if (str == "") {
$txtHint.html('');
return;
}
$txtHint.load('rfq_list.php?q=' + str) // or rfq_list.php?q
}
</script>
</head>
<body onload=showUser(str="ALL")>
<select>
<option value="r">rfq</option>
<option value="n">nego</option>
</select>
<?php
if (isset($_POST['n'])) {
$mysqli = new mysqli("localhost", "root", "", "app");
$result = $mysqli->query("SELECT nego FROM purchase_order GROUP BY shop ORDER BY nego");
$option = '';
while($row = $result->fetch_assoc()) {
$option .= '<option value = "'.$row['nego'].'">'.$row['nego'].'</option>';
}
}
?>
<?php
if (isset($_POST['r'])) {
$mysqli = new mysqli("localhost", "root", "", "app");
$result = $mysqli->query("SELECT rfq FROM purchase_order WHERE rfq LIKE '13-___' OR rfq LIKE '1_-___' OR rfq LIKE '2_-___' GROUP BY rfq ORDER BY rfq");
$option = '';
while($row = $result->fetch_assoc()) {
$option .= '<option value = "'.$row['rfq'].'">'.$row['rfq'].'</option>';
}
}
?>
<select name="users" onchange="showUser(this.value)" style="overflow:scroll;width:100px;">
<option value="ALL" selected='ALL'>ALL</option>
<?php echo $option; ?>
</select>
<div id="txtHint"></div>

Categories