I'm working on these codes for awhile and need some help. Basically, I'm trying to get the result or output of the script and put it in between the option select as shown here:
<select class="form-control" name="property_list">
*insert output javascript here
</select>
Below is the complete script. Would this method be possible?
<script>
$(document).ready(function(){
$("#client-list").on('change', function postinput(){
var matchvalue = $(this).val(); // this.value
$.ajax({
url: 'sql/client-to-property.php',
data: { matchvalue: matchvalue },
type: 'post'
}).done(function(responseData) {
console.log('Done: ', responseData);
}).fail(function() {
console.log('Failed');
});
});
});
</script>
<div class="input-group mb-3">
<span class="input-group-addon gi data-gi-size gi-user-add"></span>
<select id="client-list" name="client-list">
<?php
$sql = "SELECT `id`, `email`
FROM `clients` ORDER BY `id` ASC";
$result = $DB_CON_C->query($sql);
if($result !== false) {
$data_row = '<option>New Client</option>' . "\n";
foreach($result as $row) {
$data_row .= '<option>' .$row['email'] . '</option>' . "\n";
}
}
unset($row);
echo $data_row;
?>
</select>
</div>
<select class="form-control" name="property_list">
*insert output javascript here
</select>
Use .html() to add returned data to the select, in your done function get select by name and add the data. This will work if the returned data is in the following format:
<option value="1">1</option>
<option value="2">2</option>
jQuery
$(document).ready(function () {
$("#client-list").on('change', function postinput(){
var matchvalue = $(this).val(); // this.value
$.ajax({
url: 'sql/client-to-property.php',
data: { matchvalue: matchvalue },
type: 'post'
}).done(function(responseData) {
console.log(responseData);
var data = JSON.parse(responseData);
$('select[name="property_list"]').html(data);
}).fail(function() {
console.log('Failed');
});
});
});
Loop through your response data and append options to your property list like so:
$(document).ready(function(){
$("#client-list").on('change', function postinput(){
var matchvalue = $(this).val(); // this.value
$.ajax({
url: 'sql/client-to-property.php',
data: { matchvalue: matchvalue },
type: 'post'
}).done(function(responseData) {
console.log('Done: ', responseData);
var data = JSON.parse(responseData); // Assuming response data is a JSON string
data.each(function(i, property) {
$("input[name=property_list]").append("<option />").text(property);
});
}).fail(function() {
console.log('Failed');
});
});
});
The options will need values as well so you can add that attribute to the options too:
$("input[name=property_list]").append("<option />").attr('value', property).text(property);
Related
I have two dropdowns. One is for selecting the Main category, the second for selecting the sub category.
I want to be able to populate the sub category based on the Main category selected.
What I have tried so far is using JQUERY and AJAX to listen to change in the value of the dropdown using jquery and send an ajax request to the relevant route.
View
<div class="form-control">
<label for="category">Category</label>
<select name="category" id="category">
<option value='Men'>Men</option>
<option value='Women'>Women</option>
<option value='Sports'>Sports</option>
</select>
</div>
<div class="form-control">
<label for="subcategory">Sub Category</label>
<select id="subcategory" name="subcategory">
</select>
</div>
AJAX and JQUERY
$("#category").on("change", function () {
$("#subcategory").empty();
showValue($(this).val());
});
var data = {};
function showValue(val) {
console.log(val);
data.category = val;
$.ajax({
url: "/admin/update-list",
type: "POST",
data: data,
success: function(result) {
updateDOM(result);
},
error: function (err) {
console.log(err);
}
});
};
var updateDOM = function (result) {
var data = result.data;
for (var i = 0; i < data.length; i++) {
console.log(data[i]);
$("#subcategory").append("<option>"+ data[i] +"</option>");
};
};
/admin/update-list Route
router.post('/update-list', (req,res,next) => {
let data = [];
let category = req.body.category;
console.log('From the ajax call, category is' + category);
if(category = "Men") {
data = [
'Sneakers',
'Boots',
'High Heels',
'Litas',
'Timbs'
];
res.status(200).json({data});
res.end();
}
else if(category = "Women") {
data = [
'Timbs'
];
res.status(200).json({data});
res.end();
}
else if(category = "Sports") {
data = [
'Soccer Boots',
'Rugby Boots'
];
res.status(200).json({data});
res.end();
}
});
No matter what option I choose, the second dropdown returns the same data.
I would do this in PHP. Hopefully this conveys what you could adapt to your situation:
<select name="foo" >
</select>
ajax call
$.ajax({
type:'POST',
url:'your_code_page.php',
data:'param1='+variable,
success:function(html){
$('[name="foo"]').html(html);
}
});
PHP post back
echo "<option value=''>Please select a thing</option>"; <<outside loop
while ($row = sqlsrv_fetch_array($results)) {
$value = $row['value'];
$display = $row['display'];
//-display the result of the array
echo "<option value= " . $value . ">" . $display . "</option>"; << options returned in post
}
I have a form which selects regions, provinces, and cities. The select options for provinces depends on the selected region and the options for cities depends on the selected province. All the options are from the database
I have already made the region show up with this code.
<select class="form-control" id="region" name="region">
<?php
if( isset($Region) && count($Region)>0 ){
foreach($Region as $Region){
echo '
<option>'.$Region['region'].'</option>
';
}
}else{
echo '
<option>NO RECORDS FOUND</option>
';
}
?>
</select>
Could you please help me on my next step which is to display the options for provinces?
<select class="form-control" id="province" name="province">
</select>
I believe after achieving this step I would be able to do the same for displaying cities. Thank you!
Database name: patrol
table name: geography
>id
>region
>province
>city
I've tried the same as this one by putting this script
<script>
$(function() {
$(document).ready(function () {
$('#region').change(function() {
var select = $('#province').empty();
$.get('script.php', {region: $(this).val()}, function(result) {
$.each(result, function(i, item) {
$('<option value="' + item.value + '">' + item.name + '</option>').
appendTo(select);
});
});
});
});
});
</script>
and having this script.php
<?php
if (isset($_GET['region'])) {
$sql = new mysqli('localhost','root','','patrol');
$region = mysqli_real_escape_string($sql,$_GET['region']);
$query = "SELECT * FROM geography WHERE region = $region";
$ret = $sql->query($query);
$result = array();
while ($row = $ret->fetch_assoc()) {
$result[] = array(
'value' => $row['id'],
'name' => $row['province']
);
}
echo json_encode($result);
}
?>
<option>'.$Region['region'].'</option>
You did not set any value in region select option.
It should be like below:
<option value="'.$Region['region'].'">'.$Region['region'].'</option>
also use console.log(result) to see you are getting expected data back or not.
Thank you for answering guys. However, I have found an answer and it did the fix. I'll post the script for others who have the same question as mine
<script type="text/javascript">
$(document).ready(function()
{
$("#region").change(function()
{
var region= document.getElementById("region").value;
var dataString = 'region='+ region;
$.ajax
({
type: "POST",
url: "get_province.php",
data: dataString,
cache: false,
success: function(html)
{
$("#province").html(html);
}
});
});
$("#region").change(function()
{
var province= document.getElementById("province").value;
var dataString = 'province='+ province;
$.ajax
({
type: "POST",
url: "get_city.php",
data: dataString,
cache: false,
success: function(html)
{
$("#city").html(html);
}
});
});
$("#province").change(function()
{
var province= document.getElementById("province").value;
var dataString = 'province='+ province;
$.ajax
({
type: "POST",
url: "get_city.php",
data: dataString,
cache: false,
success: function(html)
{
$("#city").html(html);
}
});
});
});
</script>
im trying to populate a select box from values in my database after the document load, or ready. I'm new to ajax and jquery, Can someone help find what's wrong to my code?
<select class="form-control sec" id="sec" name="sec">
<option value="sec">Section</option>
</select>
here's my ajax code.
function loadselectbox(){
var fac_code = $("#faculty_code").val();
$.ajax({
type: 'POST',
url: 'getrecords.php',
data: {
"load": 1,
"fac_code": fac_code
},
dataType: 'json',
success: function(data)
{
var select = $("#sec"), options = '';
for(var i=0;i<data.length; i++)
{
options += "<option value='"+data[i].section+"'>";
}
select.append(options);
}
});
}
here's my getrecords.php
if (isset($_POST['load'])) {
$fac_code = $_POST['fac_code'];
$select = mysqli_query($con,"SELECT * FROM tfile WHERE faculty_code = '$fac_code'");
while ($row = mysql_fetch_array($select)) {
$result[] = array(
'section' => $row['section'],
'subj_descr' => $row['subj_descr']
);
}
echo json_encode($result);
}
i call the function in document.ready
$(document).ready(function() {
loaddata();
loadselectbox();
});
Try this:
$(document).ready(function(){
var fac_code = $("#faculty_code").val();
$.ajax({
url: 'getrecords.php',
type: 'POST',
data: {
"load": 1,
"fac_code": fac_code
},
success: function(response){ // response contains json object in it
var data = JSON.parse(response);
var options = '<option value=""></option>';
for(var i=0;i<data.length; i++)
{
options += "<option value='"+data[i].section+"'> +data[i].subj_descr+ </option>";
}
$("#sec").html(options); // It will put the dynamic <option> set into the dropdown
}
});
});
i need to get a value from the a form then send it to php using jquery then output the result a dropdown select menu
get the value of using jquery
<input id="search" name="search" type="text">
send it to php and perform a query
<select id="farmertype" name="farmertype" >
<option value="" > - PLEASE SELECT FARM -</option>
//// output here as options
</select>
my php file farm.php
<?php
include_once("../init.php");
$q = ($_POST["search"]);
$db->query("SELECT * FROM farmers ");
while ($line = $db->fetchNextObject()) {
$idno = $line->idno;
echo "<option value='$idno'>$idno</option>";
}
}
?>
the jquery part is so messy this is where i really need help
$("#search").click(function() {
search = $(this).attr('#search');
$.ajax({
type: 'GET',
url: 'farm.php',
data: "#search=" + search,
});
});
try this, it will help you.
JQuery:
$("#search").click(function() {
search = $(this).val();
$.ajax({
type: 'POST',
url: 'farm.php',
data: {searchValue:search},
success:function(result) {
console.log(result);
}
});
});
PHP:
<?php
include_once("../init.php");
$q = ($_POST["searchValue"]);
$db->query("SELECT * FROM farmers");
$result = [];
while ($line = $db->fetchNextObject()) {
$idno = $line->idno;
$result = "<option value='$idno'>$idno</option>";
}
print_r($result);
?>
what is the purpose of your variable $q?
Your jquery can be like :
$("#search").click(function() {
search = $('#search').val();
$.ajax({
type: 'GET',
url: 'farm.php',
data: {search : search},
success: function(html){
alert(html);
}
});
});
$("#search").click(function() { /* I think you should use keyUp or use click on a button, nobody clicks an input box */
var search = $(this).val();
$.ajax({
method: 'POST', //
url: 'farm.php',
data: {'search' : search},
success: function(data){
alert(data);
}
});
});
I'm new with JSON. I have a select box and JavaScript change() trigger on it. I execute MySQL query with Ajax based on selected value. Query results will be printed as a new row in HTML table.
But the new row isn't appending. What am I doing wrong?
HTML
<select id="orderAddProduct">
<option value=""></option>
<option value="0001">Product 1</option>
<option value="0002">Product 2</option>
</select>
<table id="orderTable">
<tr><th>ID</th><th>Name</th></tr>
</table>
JavaScript
$("#orderAddProduct").change(function () {
var element = $(this);
var selectedValue = $(this).val();
$.ajax({
type: "POST",
url: "orderAddProduct.php",
data: {option: selectedValue},
datatype: "json",
success: function (data) {
alert("OK");
orderAddRow(data);
},
error: function () {
alert("ERROR");
}
});
});
function orderAddRow($item) {
$.each($item,function(index,value) {
var row = '<tr><td>'+value.id+'</td>'
+'<td>'+value.name+'</td></tr>';
$('#orderTable').append(row);
)};
}
PHP
try {
$pdo = new PDO(DB_TYPE . ':host=' . DB_HOST . '; dbname=' . DB_NAME, DB_USER, DB_PASS);
} catch (PDOException $e) {
die("ERROR: " . $e->getMessage());
}
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec("SET NAMES utf8");
$productId = $_REQUEST['option'];
$sql = $pdo->prepare("SELECT * FROM products_view WHERE id = ?");
$sql->execute(array($productId));
$row = $sql->fetch(PDO::FETCH_ASSOC);
$json_array = array("ID" => $row['id'], "name" => $row['name']);
echo json_encode($json_array);
Variable names?
function orderAddRow($item) {
^^^^^^----
var row = '<tr><td>'+value.id+'</td>'
^^^^^----
You define a $item parameter, but never use it in the function. Instead there's this mysterious/undefined value.
Ok, the master problem is that I didn't have JSON.parse() function in my code. Below is my finally working code.
$("#orderAddProduct").change(function () {
var element = $(this);
var selectedValue = $(this).val();
$.ajax({
type: "GET",
url: "orderAddProduct.php",
data: {option : selectedValue},
datatype: "json",
success: function (response) {
response = JSON.parse(response);
if(response === undefined) {
alert("undefined");
} else {
orderAddRow(response);
}
},
error: function () {
alert("ERROR");
}
});
return false;
});
function orderAddRow($data) {
$.each($data,function(index,value) {
var row = '<tr><td>' + value.ID + '</td>'
+ '<td>' + value.name + '</td></tr>';
$('#orderTable').append(row);
});
}
success: function (data) {
alert("OK");
orderAddRow(data);
},
You are missing out the returned value.