I have a db table of all postcodes in the UK and want to create functionality to filter down into local locations to decrease load times of the page. The issue I am having is that I am a bit out of practice with JQuery and there seems to be an issue where selecting the country is not being picked up by the JQuery.
Here is the HTML/PHP for the select:
<label for="country_select">
Select Country
</label>
<select id="country_select" name="country_select" class="form-control search-select">
<option value=""> </option>
<?PHP
if ($result = mysqli_query($link, "SELECT DISTINCT(`country`) as countrylist FROM `postcodes`")) {
while($member = mysqli_fetch_assoc($result)) {
$country=$member['countrylist'];
?>
<option value="<?PHP echo $country; ?>"><?PHP echo $country; ?></option>
<?PHP
}
}
?>
</select>
Here is the PHP to check for the post and create a mysql statment to then create another drop down for cities. I am wondering if the issue lies here, i added an echo to see if it appears when the option has been changed, but nothing is appearing.
<?PHP
if (isset($_POST['CountryID'])) {
$country_query = $_POST['CountryID'];
$statement = " AND `country` = '".$country_query."' ";
echo $statement;
}
?>
And here is the jquery:
$(document).ready(function(){
$("#country_select").change(function () {
var country_name = $("#country_select").val();
jQuery.ajax({
type: "POST",
data: {CountryID: country_name},
success: function(data){
if(data.success == true){
alert('success');
}
}
});
});
});
I am unsure where I am going wrong as it has been a while since I have coded. I have looked around at others' issues with no luck. Any help would be greatly appreciated.
The issue was the jquery. The code should be the following:
$(document).ready(function(){
$("#country_select").change(function () {
var country_name = $("#country_select").val();
jQuery.ajax({
type: "POST",
data: {CountryID: country_name},
success: function(data){
alert(data);
}
});
});
});`
Related
I'm trying to fetch mutiple values from database using ajax php.
I've a select option(value is fetching from database), and if i select any option then i want to display the related data which is matching with the id
of the the current option.but currently i'm able to fetch only one data column from databse.
I'm writing my current code please have a look at it and let me know how can i modify it.
My select option:-
<select data-placeholder="Choose a Vehicle..." class="chosen-select form-control" tabindex="-1" name='vno' onChange="getCity(this.value);" id="vno" required='true' >
<option value="">Select</option>
<?php
foreach($results as $vd) { ?>
<option value='<?php echo $vd['id'];?>'><?php echo $vd['vno'];?></option>";
<?php } ?>
</select>
and the js file
// Fetch city from Database
function getCity(val) {
$.ajax({
type: "POST",
url: "retrive_data.php",
data:'id='+val,
success: function(data){
$("#rate").html(data);
}
});
}
retrive_data.php
<?php
require_once ("dbController.php");
$db_handle = new DBController();
if (! empty($_POST["id"])) {
$query = "SELECT * FROM tbl_vehicle WHERE id = '" . $_POST["id"] . "' ";
$results = $db_handle->runQuery($query);
?>
<?php
foreach ($results as $city) {
?>
<option value="<?php echo $city["rate"]; ?>"><?php echo $city["rate"]; ?></option>
<?php
}
}
?>
Change your js code as below
// Fetch city from Database
function getCity(val) {
$.ajax({
type: "POST",
url: "retrive_data.php?id=" + val,
success: function(data){
$("#rate").html(data);
}
});
}
I’m making some assumptions about the desired result, and I’m not sure what the connection is between vehicles and city rates... but there are multiple issues here. Let’s work through them:
<select data-placeholder="Choose a Vehicle..." class="chosen-select form-control" tabindex="-1" name='vno' id="vno" required='true' >
<option value="">Select</option>
<?php foreach($results as $vd): ?>
<option value="<?= $vd['id']?>" ><?= $vd['vno'] ?></option>";
<?php endforeach; ?>
</select>
<!-- add a landing spot for the data coming in -->
<select id="rate"></select>
Nothing major here, just took out the onChange (typical practice is to have a listener in the JavaScript. Separation of concerns)
In your JavaScript, I don’t think you were successfully passing the id. It should be a JavaScript object. Also, send data to a function that knows how to put the data in your form:
// Fetch city from Database
function getCity(val) {
$.ajax({
type: "POST",
url: "retrive_data.php",
data:{id: val},
success: function(data){
showRate(data);
}
});
}
Monitor the select for a change. (JavaScript should be inside document ready block)
$('#vno').on('change', function (){
getCity($(this).val());
});
Function to display the results of your ajax call:
showRate(data) {
// this lets you see the data that was returned
console.log(data);
var rate = $('#rate');
// clear current content
rate.html('');
// create options, assuming this is a select
$.each(data, function() {
rate.append($("<option />").val(this.rate).text(this.rate));
});
}
retrieve.php
Need to use prepared statements, and sending data as json instead of html is recommended
<?php
// sending json (data), not html (presentation)
header('Content-Type: application/json');
require_once ("dbController.php");
$db_handle = new DBController();
if (! empty($_POST["id"])) {
// substituting variables in a query is a big no-no
// $query = "SELECT * FROM tbl_vehicle WHERE id = '" . $_POST["id"] . "' ";
// must use placeholders / prepared statement
$query = "SELECT * FROM tbl_vehicle WHERE id = ?'";
// check your database object for how to do prepared statements and row fetching. If it doesn’t do prepared statements, dump it!
$stmt = $db_handle->prepare ($query);
$stmt->execute($_POST["id"]);
$out = array();
while($row = $stmt->fetch() ) {
$rate = $row['rate'];
$out[] = array(
'rate'=>$rate
);
}
die(json_encode($out));
}
Caveat: all code is off the top of my head, and typed on a phone. Syntax errors are likely. This is intended to show concepts and ideas for further research
I am working on project that uses a dynamic or dependent dropdown list on CodeIgniter. This is my noob logic, the country value from Views passed to Models, then the Models get state data with same country value from Views, then Controllers get state data from that Models and pass it again to Views. And the problem is the state dropdown list show nothing.
Sorry, iam new in coding.
//This is the Controllers (Pkl.php)
$data['all_country'] = $this->Server_Model->get_country_model();
$data['all_state'] = $this->Server_Model->get_state_model();
$this->load->view('contents/page_dashboard', $data);
//This is the Models (Server_Model.php)
function get_country_model(){
$db_jarlap = $this->load->database('gis_bali', TRUE);
$db_jarlap->select("*");
$db_jarlap->from("country");
$que = $db_jarlap->get();
return $que->result();
}
function get_state_model(){
$kakakoko = filter_input(INPUT_POST, 'country_id');
$db_jarlap = $this->load->database('gis_bali', TRUE);
$db_jarlap->select("*");
$db_jarlap->from("state");
$db_jarlap->where(" id_country = $kakakoko ");
$que = $db_jarlap->get();
return $que->result();
}
//This is the Views Content (page_dashboard.php)
<script src="<?php echo base_url() ?>resources/js/jquery-3.3.1.min.js"</script>
<script>
$(document).ready(function(){
$('#formCountry').change(function(){
var country_id = $(this).val();
$.ajax({
url: "<?php echo base_url() ? >application/models/Server_Model.php",
method: "POST",
data: {country_id:country_id},
success: function(data) {
$('#formState').html(data);
}
});
});
});
</script>
<select name="formCountry" id="formCountry">
<?php foreach($all_country as $semua_country): ?>
<option value="<?php echo $semua_country->id_country; ?>"><?php echo $semua_country->nama_country; ?></option>
<?php endforeach; ?>
</select>
<select name="formState" id="formState" >
<?php foreach($all_state as $semua_state): ?>
<option value="<?php echo $semua_state->id_state; ?>"><?php echo $semua_state->nama_state; ?></option>
<?php endforeach; ?>
</select>
Thanks for your help.
You should not directly call model, instead call the Pkl controller, I'm assuming that you are using the index() method on Pkl controller :
$(document).ready(function () {
$('#formCountry').change(function () {
var country_id = $(this).val();
$.ajax({
url: "<?php echo base_url() ?>pkl", // using Pkl controller
method: "POST",
data: {
country_id: country_id
},
success: function (data) {
$('#formState').html(''); // empty the select option element
$.each(data, function(){ // format each option returned from Pkl controller
$("#formState").append('<option value="'+ this.id_state +'">'+ this.nama_state +'</option>');
});
}
});
});
});
Good day to everyone. So I am trying to get the value of a select option and getting a set of rows in MySql depending on the column name in the database. So here is the HTML code:
<html>
<body>
<select name = "FilterDoc" onchange = "filterby(this);">
<option disabled>Filter By</option>
<option value="document_type">Document Type</option>
<option value="date">Date</option>
<option value="hei">HEI</option>
<option value="other">Other Govt.</option>
<option value="person">Person</option>
</select>
<div class="panel-body" id="container">
</div>
Here is code for Ajax:
<script type="text/javascript">
function filterby(sel){
$.ajax({ //create an ajax request to display.php
type: "POST",
data: {FilterDoc: $(sel).val()},
url: "filterdocu.php",
dataType: "html", //expect html to be returned
success: function(response)
{
$("#responsecontainer").html(response);
}
console.log(reply);
});} </script>
Now the value of the select option will pass to the PHP file. I dont know if "if statement" is the right one for this since I haven't had that much background about getting values on html and such and I'm trying to find a better way to get the rows from MySql and display them into the container.
Here's the PHP code:
<?php echo"<div class='panel panel-primary' id='container'>";
if($_POST["FilterDoc"]=="document_type")
{
echo "<script type='text/javascript'>$('container').html('""');</script>";
$result=mysqli_query($conn,"SELECT * FROM records ORDER BY document_type ASC");
while($data = json_encode(mysql_fetch_assoc($result))
{
echo json_encode($data);
}
}
else if($_POST["FilterDoc"]=="date")
{
$result=mysqli_query($conn,"SELECT * FROM records ORDER BY date_received DESC");
echo "<script type='text/javascript'>$('container').html('""');</script>";
while($data = json_encode(mysql_fetch_assoc($result))
{
echo json_encode($data);
}
}
else if($_POST["FilterDoc"]=="hei")
{
$result=mysqli_query($conn,"SELECT * FROM records ORDER BY hei ASC");
echo "<script type='text/javascript'>$('container').html('""');</script>";
while($data = json_encode(mysql_fetch_assoc($result))
($result))
{
echo json_encode($data);
}
}
else if($_POST["FilterDoc"]=="Other")
{
$result=mysqli_query($conn,"SELECT * FROM records ORDER BY other_govt ASC");
echo "<script type='text/javascript'>$('container').html('""');</script>";
while($data = json_encode(mysql_fetch_assoc($result))
{
echo json_encode($data);
}
}
else if($_POST["FilterDoc"]=="Person")
{
$result=mysqli_query($conn,"SELECT * FROM records ORDER BY contact_person ASC");
echo "<script type='text/javascript'>$('container').html('""');</script>";
while($data = json_encode(mysql_fetch_assoc($result))
{
echo json_encode($data);
}
}echo"</div>"; ?>
I'm also not entirely sure if using javascript to clear the container is the proper way before putting contents into the div container.
I would really appreciate your help. Thank you!
At first i would simplify the code like :
<?php
echo "<div class='panel panel-primary' id='container'>";
// Set Variable
$filter = $_POST["FilterDoc"]; // This needs proper escaping
$result = mysqli_query($conn,"SELECT * FROM records ORDER BY $filter ASC");
while($data = json_encode(mysql_fetch_assoc($result)) {
echo json_encode($data);
}
echo "</div>";
Thats the PHP part, now i would rewrite the javascript.
function filterby(sel) {
$.ajax({ //create an ajax request to display.php
type: "POST",
data: {
FilterDoc: $(sel).val()
},
url: "filterdocu.php",
dataType: "html", //expect html to be returned
success: function(response) {
$("#container").empty().html(response);
}
});
}
But maybe your whole filtering process may be inefficient. You could fetch all the data with one SQL call and do the filtering with JS / data-attributes.
I have the following dropdown list which changes the output of <div id="item"></div> with ajax when select option is changed. I'm not using select2.
<?php
$biqsQuery = "SELECT biq.biqid, biq.name FROM biq";
$biqs = $db->query($biqsQuery);
?>
<select name="itemselector" id="itemselect">
<?php foreach ($biqs ->fetchAll() as $biq): ?>
<option value="<?php echo $biq['biqid']);?>">
<?php echo e($biq['name']);?>
</option>
<?php endforeach; ?>
</select>
<div id="item"></div>
PHP File:
if(isset($_GET['itemselector'])){
$biqQuery = "SELECT biq.biqid, biq.name, biq.img
FROM biq
WHERE biq.biqid= :biqid ";
$biq= $db ->prepare($biqQuery);
$biq->execute(['biqid' => $_GET['itemselector']]);
$selectedBiq=$biq->fetch(PDO::FETCH_ASSOC);
echo '<img src="'. $selectedBiq['img']. '">';
}
Javascript File:
$('#itemselect').on('change',function(){
var self = $(this);
$.ajax({
url: '../helpers/biq.php',
type: 'GET',
data: {itemselector : self.val()},
success: function(data){
$('#item').html(data);
}
});
});
It's currently succesfully changing the output, no problem on that part.
But when the page is first loaded, it shows the first value of the table on the dropdown menu, however it doesnt output the image of that first value into <div>.
What i need is; when the page is loaded i need the first entry in the database to be outputted into the <div id="item"></div> automatically.
Any help is appreciated, thanks in advance.
you could write on body load event to accomplish this. please correct if any type mistake will there but this will help you to get it rid
$(document).ready(function(){
var first = $("#itemselect option:first").val();
$.ajax({
url: '../helpers/biq.php',
type: 'GET',
data: {itemselector : first},
success: function(data){
$('#item').html(data);
}
});
});
I have a dependent dropdown menu for category>subcategory without refreshing page with the help of Ajax. But currently my JavaScript code sends the Ajax request to another page and it works fine, i want to send the request to the same page. Currently using the JavaScript as below .. please anyone help me to get the request to the same page.
<script type="text/javascript">
$(document).ready(function(){
$(".category").change(function(){
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax({
type: "POST",
url: "ajax-subcat.php",
data: dataString,
cache: false,
success: function(html){
$(".subcat").html(html);
}
});
});
</script>
If I empty the Ajax url, still doesn't work for one page.
HTML as below
<select name="category" class="category">
<option selected="selected">--Select Category--</option>
<?php
$sql=mysqli_query($mysqlCon, "SELECT * FROM category WHERE catid=1");
while($row=mysqli_fetch_array($sql)){
$cat_id=$row['catid'];
$data=$row['catname'];
echo '<option value="'.$cat_id.'">'.$data.'</option>';
}
?>
</select>
<label>Subcategory:</label>
<select name="subcat" class="subcat">
</select>
ajax-subcat.php contains the below
if(isset($_POST['id'])){
$id=$_POST['id'];
$sql=mysqli_query($mysqlCon, "SELECT * FROM subcategory WHERE sucat='$id'");
while($row=mysqli_fetch_array($sql)){
$id=$row['sucat'];
$data=$row['sucat_name'];
echo '<option value="'.$id.'">'.$data.'</option>';
}
}
I want to achieve this in 1 page, without sending request to other page. Please help.
Please remember to properly indent your code and make the necessary spaces for readability. Also, I advise you to separate your code, and put all the PHP part in classes provided for that purpose.
Try this :
Html file
<select id="category">
<?php
$sql = mysqli_query($mysqlCon, "SELECT * FROM category WHERE catid=1");
while($row=mysqli_fetch_array($sql)) {
$cat_id=$row['catid'];
$data=$row['catname'];
echo '<option value="'.$cat_id.'">'.$data.'</option>';
}
?>
</select>
<label>Subcategory :</label>
<select id="subcat"></select>
<!-- Suppose you call the jquery here -->
<script type="text/javascript">
$(document).ready(function() {
$('#category').change(function () {
var id = $(this).val();
$.ajax({
type: 'POST',
url: 'ajax-subcat.php',
data: json,
cache: false
}).done(function (data) {
$('#subcat').html(data);
}).fail(function (data) {
alert('You have a critic error');
});
});
});
</script>
You should call the php script with json, and have the callback with json_encode. This approach is cleaner. Also I set you the new ajax syntax. THe syntax you used with "success" is now deprecated.
Php file
<?php
if(isset($_POST['id']) && !empty($_POST['id'])) {
$id = $_POST['id'];
$sql = mysqli_query($mysqlCon, "SELECT * FROM subcategory WHERE sucat='$id'");
while($row = mysqli_fetch_array($sql)) {
$id = $row['sucat'];
$data = $row['sucat_name'];
$return[] = '<option value="'.$id.'">'.$data.'</option>';
}
echo json_encode($return);
}
?>
Code not tested, but I think it work