I am having problems displaying the names of golf courses in my dropdown menu. I have a PHP script that when ran, returns the names of the courses in my database. The problem is that when I apply this to my index.html dropdown page and display it in the browser, the content is not displaying the dropdown.
<?php
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_name = '';
$con = mysqli_connect($db_host,$db_user,$db_pass, $db_name);
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$sql = "SELECT name FROM courses";
$result = mysqli_query($con, $sql) or die("Error: ".mysqli_error($con));;
$courses = array();
while ($row = mysqli_fetch_array($result))
{
array_push($courses, $row["name"]);
}
echo json_encode($courses);
?>
The above code successfully generates the data from the database
$(document).ready(function () {
$.getJSON("getCourseDD.php", success = function(data){
var options = "";
for(var i=0; i< data.length; i++){
options += '<option value ="' + data[i] + '">' + '</option>';
}
$("#selectCourse").append(options);
});
});
The above code is not populating the course names into the dropdown menu.
The id of my dropdown menu is selectCourse.
<form> <select id="selectCourse" </select> </form>
Thanks for any help in advance.
You need to put text in options as below :
var dummyData = ['English','Spanish','French','Mandarin'];
$(document).ready(function () {
var data = dummyData, //This data comes from the ajax callback
courseOptions = "";
for(var i=0; i< data.length; i++){
courseOptions += '<option value ="' + data[i] + '">'+data[i]+'</option>';
}
$("#selectCourse").append(courseOptions);
});
Working Demo : jsFiddle
Currently you are not setting text of option also, use
options += '<option value ="' + data[i] + '">' + data[i] + '</option>'
instead of
options += '<option value ="' + data[i] + '">' + '</option>';
As you're currently utilizing jQuery, you may want to go for this solution:
for(var i=0; i< data.length; i++)
{
$("#selectCourse").append(
$('<option>').text(data[i]).val(data[i])
);
}
Use .html(options); in place of .append(options); .
append() add data after tag but html() insert data between tag.
and you should also assign something between tag, like
options += '<option value ="' + data[i] + '">' + data[i] + '</option>'
First log your data like console.log(data) and check in browser firebug console whether it outputs json string or object. If it's string you need to convert it into object using JSON.parse().
Related
I'm trying to populate a Drop-Down menu from a csv file located on a network share.
I've come as far to get the file to create all the options successfully when the file is in the wwwroot folder however, now I'm faced with the external url reference issue.
Ajax does not support local File:/// directories and when attempting to use the network share location it also fails: \\Server\Folder\File.csv
Is there any way to read the data from the csv file using php or other server-side language in order to perform my work on the data?
Code Below for your reference:
<script>
function SubmitBy(){
$.ajax({
url: encodeURI('./PrinterLookup.csv'),
success: function(data) {
var splitData=data.split("\n");
for (var i = 0; i < splitData.length; i++) {
var colData = splitData[i];
var strucData = colData.substr(0, colData.indexOf("="));
$('#SubmitBy').append("<option value=\"" + strucData + "\">" +
strucData + "</option>");
}
}
});
}
</script>
Looking for something like this,,, to bypass the ajax url limitation:
<script>
function SubmitBy(){
<?php
$Datapath = "\\Server\Folder\Document.csv";
$Data = file_get_contents($Datapath);
?>
var data = $Data;
var splitData=data.split("\n");
for (var i = 0; i < splitData.length; i++) {
var colData = splitData[i];
var strucData = colData.substr(0, colData.indexOf("="));
$('#SubmitBy').append("<option value=\"" + strucData + "\">" +
strucData + "</option>");
}
}
});
}
</script>
Any assistance on this will be greatly appreciated.
Thank you in advance.
in this line var data = $Data; you need to print $Data see below
<script>
function SubmitBy(){
<?php
$Datapath = "file:///Server/Folder/Document.csv";
$Data = file_get_contents($Datapath);
?>
var data = <?php echo $Data; ?> //correction here
var splitData=data.split("\n");
for (var i = 0; i < splitData.length; i++) {
var colData = splitData[i];
var strucData = colData.substr(0, colData.indexOf("="));
$('#SubmitBy').append("<option value=\"" + strucData + "\">" +
strucData + "</option>");
}
}
});
}
</script>
Please check first this is .php file .
If this is .php file.
<?php
$Datapath = "\\Server\Folder\Document.csv";
$Data = file_get_contents($Datapath);
?>
<script>
function SubmitBy(){
var data = <?php print_r( $data ); ?>;
var splitData=data.split("\n");
for (var i = 0; i < splitData.length; i++) {
var colData = splitData[i];
var strucData = colData.substr(0, colData.indexOf("="));
$('#SubmitBy').append("<option value=\"" + strucData + "\">" +
strucData + "</option>");
}
}
});
}
</script>
I have to append data one by one by clicking button
$(document).ready(function() {
var i = 0;
$("#add_row").click(function() {
$('#addr' + i).html("<td>" + (i + 1) + "</td><td><select id='myselect" + i + "' name='job_id[]" + i + "' class='form-control'><option value=''>Select the Job</option><?php
$mysql = "select * from ca_job where job_status != 'Closed' and job_customer_name = '".$com_id.
"'"; $result1 = mysql_query($mysql) or die(mysql_error());
while ($roww = mysql_fetch_array($result1)) {
$sql = "select * from `ca_job_type` where `jtype_id`= '".$roww['job_type'].
"'";
$res = mysql_query($sql) or die(mysql_error());
$row1 = mysql_fetch_array($res);
echo '<option value='.$roww['job_id'].
' selected>'.$roww['job_id'].
'-'.$row1['job_type_name'].
'</option>';
} ? > < /select></td > < td > < input name = 'invoice_description[]"+i+"'
type = 'text'
placeholder = 'invoice_description'
class = 'form-control input-md'
id = 'invoice_description' / > < /td><td><input name='sac_hsc_code[]"+i+"' type='text' placeholder='sac_hsc_code' class='form-control input-md'id='sac_hsc_code' / > < /td><td><select id='employee' name='tax_id[]"+i+"' class='form-control'><option value=''>Please select</option > <?php
$sql = "select tax_id, tax_type, tax_comp, tax_Percent FROM ca_taxmaster where tax_comp = '0'";
$resultset = mysql_query($sql) or die(mysql_error());
while($rows = mysql_fetch_array($resultset)) { echo '<option value='.$rows['tax_id'].' selected>'.$rows['tax_type'].'</option>'; } ?> < /select></td > < td > < input name = 'amount[]"+i+"'
type = 'text'
placeholder = 'amount'
class = 'form-control input-md' / > < /td>"
);
Above source which I have posted was multiple input type up to that working but after selecting drop-down of id='myselect' for first list it was showing the values if press (+) button above value get cleared and showing last data alone but I need the values of first row and second row.
$(document).ready(function() {
$('#myselect' + i).change(function() {
var job_id = $(this).find(":selected").val();
var dataString = 'job_id=' + job_id;
$.ajax({
url: '<?=base_url(); ?>ajax/getjob.php',
dataType: "json",
data: dataString,
cache: false,
success: function(employeeData) {
$('.appendData').empty();
if (employeeData) {
$("#dvPassport").show();
$("#dvPassport1").hide();
var myselect = [employeeData];
employeeData.forEach(function(item) {
var data = '<tr>';
data += '<td>' + item.job_id + '</td>';
data += '<td>' + item.disburse_Date + '</td>';
data += '<td align="right">' + item.approved_amount + '</td>';
data += '</tr>';
$('.appendData').append(data);
});
} else {
$("#dvPassport").hide();
$("#dvPassport1").show();
} //else
}
});
});
});
$('#tab_logic').append('<tr id="addr' + (i + 1) + '"></tr>');
i++;
});
$("#delete_row").click(function() {
if (i > 1) {
$("#addr" + (i - 1)).html('');
i--;
}
});
});
Please click here to get clear view
In the above picture if I have selected dropdown two values showing and I am pressing the + button and selecting second drop-down first values getting cleared and showing second value what I have selected in the last dropdown. but I need the values of the first drop-down and second drop down.Please help me if anyone faces this problem .Thanks in advance.
i am not quit sure what you are trying to achieve but you forgot some ticks in for the value in the dropdowns, which might solve your problem
change
echo '<option value='.$roww['job_id'].' selected>'.$roww['job_id'].
to
echo '<option value="'.$roww['job_id'].'" selected>'.$roww['job_id'].
and
echo '<option value='.$rows['tax_id'].' selected>'.$rows['tax_type'].'</option>';
to
echo '<option value="'.$rows['tax_id'].'" selected>'.$rows['tax_type'].'</option>';
beside that
you should really consider formating your code well, it is very hard to read and understand and therefore very hard to debug
try to divorce your source, try to not mix php, html and javascript. it is possible to use it that way, but it also is a huge error source and very hard to maintain
use the mysqli functions instead of mysql -> MySQL Improved Extension
I have a select list that is dynamically filled with data from my database. But I don't want the users to see the real column names, so I created a extra column in my database called column_alias. What I want, is to show the column_alias names in the dropdown but keep the real values of column names.
This is how I'm filling the select list with the real column names at the moment:
function loadTables() {
$.getJSON("dropdown_code/get_tables.php", success = function(data)
{
console.log('inside callback');
var optionsTables = "";
for(var i = 0; i < data.length; i++)
{
optionsTables += "<option value='" + data[i] + "'>" + data[i] + "</option>";
}
$("#slctTable").append(optionsTables);
$("#slctTable").change();
});
}
And this is the code that get's the data outof my database:
<?PHP
require "opendb.php";
$query = "select table_name
from db_tables
order by table_name";
$data = pg_query($conn, $query);
$table_names = array();
while ($row = pg_fetch_array($data))
{
array_push($table_names, $row["table_name"]);
}
echo json_encode($table_names);
require "closedb.php";
?>
Update
This is what my database table looks like:
So I want the table_alias to be visible in my select list, but I want the value to be table_name so it can interact with my database.
Firstly you will need to fetch the alias as well from the database.Change your server side code to the following.
<?PHP
require "opendb.php";
$query = "select table_name,table_alias
from db_tables
order by table_name";
$data = pg_query($conn, $query);
$table_names = array();
while ($row = pg_fetch_array($data))
{
array_push($table_names, $row);
}
echo json_encode($table_names);
require "closedb.php";
?>
Then in your client side code simply output the table_alias as option name and table_name as option value.
function loadTables() {
$.getJSON("dropdown_code/get_tables.php", success = function(data)
{
console.log('inside callback');
var optionsTables = "";
for(var i = 0; i < data.length; i++)
{
optionsTables += "<option value='" + data[i]['table_name'] + "'>" + data[i]['table_alias'] + "</option>";
}
$("#slctTable").append(optionsTables);
$("#slctTable").change();
});
}
html
<select id="xoxo_select">
<option value="foo_value">foo</option>
<option value="xoxo_value">xoxo</option>
</select>
js
$('#xoxo_select option[value="xoxo_value"]').text('bar'); // change name of option
$('#xoxo_select option[value="xoxo_value"]').attr('value', 'bar_value'); // change value of option
jsfiddle https://jsfiddle.net/tg126u7g/
Change in fetch data from DB:
<?PHP
require "opendb.php";
$query = "select table_name,table_alis
from db_tables
order by table_name";
$data = pg_query($conn, $query);
$table_names = array();
$i=0;
while ($row = pg_fetch_array($data))
{
array_push($table_names[$i], $row["table_name"]);
$i++;
}
echo json_encode($table_names);
require "closedb.php";
?>
Then Change in javascript code:
optionsTables += "<option value='" + data[i][0] + "'>" + data[i][1] + "</option>";
Apologies if this has been answered before but I couldn't find what I was looking for. So, I use $.getJSON to send some variables to a php file. The file returns success as true but for some reason always triggers the .fail function.
The weird thing is, it all works fine on my laptop, just not on the computer at university. Connection to the database is fine, like I said everything works and it returns all the correct data but doesn't trigger the success function.
JQuery:
function request_user_review() {
$.getJSON("user_review_list.php", success_user_review).fail(fail_user_review);
}
function success_user_review(response) {
if (response.success) {
var user_review_list = "";
$("#user_reviews .review_cafe").remove();
$("#user_reviews .review").remove();
$("#user_reviews .rating").remove();
$("#user_reviews .review_choice").remove();
for (var i = 0; i < response.rows.length; i++) {
var review_cafe = '<tr id="row_' + response.rows[i].id + '"><td class="review_cafe">'
+ response.rows[i].cafe + '</td>';
var review = '<td class="review">'
+ response.rows[i].review + '</br>Review left: ' + response.rows[i].date + '</td>';
var rating = '<td class="rating">'
+ response.rows[i].rating + '/5</td>';
var review_choice = '<input type="hidden" class="cafe_id" value="' + response.rows[i].cafe_id + '" /><td class="review_choice"><button onclick="request_edit(this.id)" id="edit_' + response.rows[i].id + '" class="btn_edit">Edit</button><button onclick="request_delete_review(this.id)" id="delete_' + response.rows[i].id + '" class="btn_delete">Delete</button></td></tr>';
user_review_list += review_cafe + review + rating + review_choice;
}
$("#user_reviews").html(user_review_list).trigger("create").trigger("refresh");
} else {
$("#review_message").html("Review failed to be loaded!").trigger("create").trigger("refresh");
}
}
function fail_user_review() {
$("#review_message").html("Connection down?").trigger("create").trigger("refresh");
}
PHP:
<?php //user_review_list.php
require_once "sql.php"; //connection to database and query is handled here
require_once "logged_in.php";
error_reporting(E_ALL ^ E_NOTICE);
ini_set('display_errors','On');
$session_id = $_SESSION['userid'][0];
$result = array();
$result['success'] = false;
$query = "SELECT * FROM reviews WHERE user = $session_id;";
if ($result_set = Sql::query($query)) {
$result['success'] = true;
$result['message'] = "Your Reviews" ;
$rows = mysqli_num_rows($result_set);
$result['rows'] = array();
for ($i = 0; $i<$rows; $i++) {
$tmpRow = mysqli_fetch_assoc($result_set);
$php_date = strtotime($tmpRow['date']);
$formatted_php_date = date('M d, Y', $php_date );
$tmpRow['date'] = $formatted_php_date;
$result['rows'][$i] = $tmpRow;
}
} else {
$result['message'] = "Failed to read Reviews" ;
}
print(json_encode($result));
Thanks
James
The messages you get mean you're trying to parse something that's already JSON. My earlier statement about parsing JSON is not going to be of much help here because you're not just getting back a string that needs to be converted to JSON -- which you really shouldn't be with $.getJSON().
You're getting back a JSON with an invalid encoding somewhere along the line, so trying to parse it won't help you. Validate your JSON first and foremost (the error could be due to your differing server settings between machines) using jsonlint, and continue from there.
I use to populate Dropdown using javascript:
function populateDDL(ddl_id) {
var option_str = "";
var x;
for(x in datalist){
option_str += " <asp:ListItem Value='" + datalist[x] + "' Text='" + datalist[x] + "'></asp:ListItem>"
}
var country_div = document.getElementById(ddl_id);
country_div.innerHTML = option_str;
}
This is sure the datalist is not empty and also Dropdown list populated perfectly..but dnt know why after clicking on my page add button I am not getting the selected value.
Thanks
You should use client side select list control rather than server control to whome you are trying to fill at client side. Its surprised ...
But you should use select control
function populateDDL(ddl_id) {
var option_str = "<select id='ddl_id'>";
var x;
for(x in datalist){
option_str += " <option value='" + datalist[x] + "'>" + datalist[x] + "</option>";
}
option_str += "</select>";
var country_div = document.getElementById(ddl_id);
country_div.innerHTML = option_str;
}