Javascript Function to populate a select menu from MySQL - php

I have this PHP Code which populates a select menu from a MySQL Database...
<select name="input" id="input">
<?php
$sql="SELECT * from table ";
$rs=mysql_query($sql,$conn) or die(mysql_error());
while($result=mysql_fetch_array($rs))
{
echo '<option value="'.$result["db_field"].'">'.$result["db_field"].'</option>';
}
?>
</select>
which works perfectly fine but i need to somehow get it into a javascript function.
I have the javascript code that when you click a button it adds more text boxes and another select menu but it does not populate the data from the database in any new (added on) select menus

You can probably convert the options into JSON using json_encode (I am not a PHP programmer and dont know exact semantics of using it)
In PHP do something like:
echo '<script>var optionsJSON = '.json_encode(mysql_fetch_array($rs)).'</script>'
In javascriptn do something like (I am using jquery):
var select = $('select.classOfThisSelect');
var options = JSON.parse(optionsJSON);
for(var i = 0; i < options.length; i++)
$('option').attr({value: options[i]}).append(options[i]).appendTo(select);
optionsJSON will be the JSON string which will be globally available
You can freely use it in your Javascript function
Note: You may need to surround the json_encode with quotes

Start by converting the string of values into an array, so you have something like:
var values = ['value0','value1','value2'];
Then you can convert them to options and add them to a select element like:
function addOptions(select, values) {
for (var i=0, iLen=values.length; i<iLen; i++) {
select.appendChild(new Option(values[i],values[i]));
}
}
And call it like:
addOptions(document.getElementById('input'), values);
after the select is added to the page.
Incidentally, you don't need to add both an id and name to form controls. You must have a name for them to be submitted, the ID is unnecessary. If you get a reference to the form you can access controls as named properties of the form, so you might reference the select using:
document.forms[0]['input'];
or
document.forms[0].input;
and so on. Note that "input" isn't a good choice of control name.

Related

Automatically update text from select via AJAX

Does anyone know how to let ajax update text from a select input.
What I mean is if you select (form -> input) something, it will update/appear in a <span> or something.
This is what I have:
<?php
echo '<select name="test">';
for ($i=0; $i <= 20; $i++) {
echo '<option value="'.$i.'">'.$i.'</option>';
}
echo "</select>";
?>
And in the <script>:
<script>
function upperCase()
{
var A = document.getElementById('test').value;
var B = document.getElementById('txtHint1').value;
C = A * B
document.getElementById('result').value = C;
}
</script>
And where I want to show it:
<span id="txtHint1" onchange="upperCase()"></span>
I hope you understand me.
I see several errors in your original question. The first of which is here:
echo "<select name="test">;
Since it's a double-quoted string, you'll need to escape the double quotes around test, or surround the string in single quotes. You're also missing a closing quote. Is should look something like this:
echo '<select name="test">';
Also, rather than binding your onchange event to where you want to show the results, bind it to the element that, when changed, you want your JavaScript to execute. In this case, that would be your select. Now we're up to this:
echo '<select name="test" onchange="upperCase()">';
This line: C = A * B should look more like:
var C = A * B;
Additionally, your code is attempting to set the value of an element with ID result. According to your post, it seems that you may want to change that to txtHint1.
I'm assuming this is your scenario:
User selects an option from a drop down box
Once they have selected their option, the value of that option multiplied by your 'txtHint1' span is shown in the 'result' span
First, you don't need ajax to do that, just JavaScript, which I'm sure you meant. Next, you don't want onchange on your 'txtHint1' span, because there's nothing to change there. You want onchange to be on your 'select' element. You were very close in your code.
function upperCase()
{
var a = document.getElementById('test').value;
var b = document.getElementById('txtHint1').value;
var c = a * b;
document.getElementById('result').value = c;
}
<select name="text" onchange="upperCase()">YOUR PHP CODE<select>
I didn't test this, but it should work.

array of same id using getElementById error

i want to create array of same id or name using getElementById..
i have a "add button", when the user press this button, its generate a dropdown list(dynamic) which the value is get from mysql..
and its looks like this when the user press 3 times..
i want to create an array of this id, and store it to mysql..
this is my JS code :
var menu_paket_array = document.getElementById('menu_paket').value;
alert(menu_paket_array);
the problem is, when i try to create this array(menu_paket_array), the value in this array is just the first id (Test 1) only..
how can i fix this?
thanks...
Using the same id for more than one element is wrong. Id is to uniquely identify certain element. Using it for more elements defeats its -purpose. If you need that for i.e. CSS styling, then use class instead, which is designed just for such scenarios.
An ID must be unique on a page. You can only use it on one element.
Instead, use a CSS class or element type to iterate (here's a fiddle demonstrating this code):
function alertValues() {
var select, selects = document.getElementsByTagName('select');
var out = "";
for (var i = 0; i < selects.length; i++) {
select = selects[i];
if (select.className && select.className.match(/CLASSNAME_TO_INCLUDE/)) {
out += select.options[select.selectedIndex].value;
}
}
alert(out);
}
A better solution, of course, would be to utilize a dom library like jQuery or mootools, with which you could do something like this:
jQuery(function($) {
vals = [];
$('select.CLASSNAME').each(function() { vals.push($(this).val()); });
alert(vals.join(','));
});
document.getElementsByClassName(names);
Where names is the classname u generate for each one.
Instead of assigning each element with id='menu_paket' (for the reasons #WebnetMobile.com explained) assign class='menu_paket'.
Instead of var menu_paket_array=document.getElementById('menu_paket').value;, do
var temp_array = document.getElementsByClassName('menu_paket');
var menu_paket_array = [];
for(i in temp_array){
menu_paket_array[] = temp_array[i].value;
}

Using one <form>'s selection to feed into another <form>?

From within php, I have a large html <form> filled out with lots rows of patient info from a postgres database. When a doctor double-clicks on a row, it sets a var in $_POST and invokes another php script to read up and display specific info about that row from the database. This all works.
But there are now so many rows of patient data that the doctors don't want to scroll and scroll to find the patient rows they're looking for, they want a patient prefilter <form> so that a click on an element in it will result in the large display filtered to just that patient's rows.
What's a basic approach to doing this? I'm a newb; I'm currently using html, php, and some javascript.
Make a second form with whatever options you'd like to filter on, this part will be specific to your data but you want something like
<form id="search-form">
<label>Name:</label><input type="text" name="patient-name"></input>
</form>
You'll need to build a query string (and make sure you use GET, because that will make things easier for you). This will require tweaking if you want to use radio buttons, or something similar, but here's the general idea:
function getSearchParameters () {
var form = document.getElementById('search-form');
var inputs = form.getElementsByTagName('input');
var result = '';
var i;
for (i = 0; i < inputs.length; i++) {
if (inputs[i].value) {
result += "&" + inputs[i].name + "=" + inputs[i].value;
}
}
return result;
}
In the onClick handler for your patient data links, you'll call this function and append its result to your query string:
element.onclick = function () {
var patientDataUrl = '/patients.php?param1=someValue';
patientDataUrl += getQueryParameters();
/* then do your ajax stuff as normal */
};
Then on the server side, within patients.php simply check for the presence of the search fields i.e.
if(isset($_GET['patient-name'])) {
$patient_name = mysql_real_escape_string($_GET['patient-name']);
$query = "SELECT * FROM `patients` WHERE `patient_name`='$patient_name';";
} else {
$query = "SELECT * FROM `patients`;";
}
(make sure you sanitize the string!)
I'd recommend considering a JS framework to make your life much easier (for instance, jQuery would allow you to send this via POST or easily serialize it into a GET query string via .serialize())

Autocomplete: populate multiple fields based on selection

I have a form, and there are 5 fields. The first field is an autocomplete field. I'd like to have the other 4 fields populated based on the autocomplete field selection. The docs in github ajax.autocompleter page reference setting an id and using a js function to call the id value, but this doesn't seem efficient if using multiple fields/need multiple values in addition to the ac value.
I'm using scriptaculous, and php. I have the autocompleter functioning, but am not sure on the rest of it. I'm also not clear on how to set the additional field parameters on the php end. I suppose that I could set the id="field1Val='blah'&field2Val='blah2'" then use js to parse and populate fields, but something about that just doesn't feel right.
Any idears?
this is what we use: a jquery plugin. The good thing about this one is that you can add a callback function that allow you to change the "current" behavior.
about the line 385 you have function that parses the result:
function parse(data) {
var parsed = [];
var rows = data.split("\n");
for (var i=0; i < rows.length; i++) {
var row = $.trim(rows[i]);
if (row) {
row = row.split("|");
parsed[parsed.length] = {
data: row,
value: row[0],
result: options.formatResult && options.formatResult(row, row[0]) || row[0]
};
}
}
return parsed;
};
you can create your own function that depending on what you get (you can send a json from the server) and then execute javascript and drive the form controls.
hope help you

Dynamically populating HTML DropDown controls using AJAX and PHP

To dynamically fill DropDown controls on my HTML Form, I have written code that makes AJAX call to a .php file. This .php file populates the DropDown control with a single column value.
In this whole process, three files play the role.
(1) A HTML file that contains the entry form,
(2) A .js file containing basic AJAX code, and
(3) A .php file containing code to populate the DropDown control on my HTML form.
Below, I am giving the necessary code of all the three files respectively. The DropDown is not populating, therefore, I want to know the necessary corrections needed in the below given code.
Please note that the MakeRequest function in the .js file, accepts few arguments. These arguments are:
(1) HTML DropDown control name,
(2) Entire Sql Query.
(3) The ID column in a MySQL table.
(4) The actual column whose values need to be populated in the DropDown control.
In this context, for example, I am referencing a MySQL table named: "ElectionCategoryMaster", that comprises of following columns:
(1) ecID Int P.K
(2) ecName varchar
I am passing ID column as a argument so that I can retrieve this ID value when the user selects an ecName from the DropDown. This, ecID, will be stored in a different table.
[Code: HTML file]
<td onactivate="javascript: MakeRequest('inCategory','SELECT * FROM electioncategorymaster', 'ecid', 'ecname');">
<select id="inCategory" name="inCategory" class="entryFormInputBoxColor">
</select>
</td>
[Code: .js file] [AJAX]
function MakeRequest(DropDownName, SqlQuery, IdColumnName, DisplayColumnName)
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
HandleResponse(xmlHttp.responseText);
}
}
xmlHttp.open("GET", "filldropdown.php?DropDownControlName = " + DropDownName + "&SqlQuery = " + SqlQuery + "&IdColumnName = " + IdColumnName + "&DisplayColumnName = " + DisplayColumnName, true);
xmlHttp.send(null);
}
function HandleResponse(response)
{
document.getElementById('ResponseDiv').innerHTML = response;
}
[Code: .php file] [To populate the desired DropDown control]
<?php
//Get values
$dropdownControlName = $_GET['DropDownControlName'];
$sqlQuery = $_GET['SqlQuery'];
$idColumnName = $_GET['IdColumnName'];
$displayColumnName = $_GET['DisplayColumnName'];
echo "dfddddf";
dbconnection::OpenConnection();
$result = dbaccess::GetRows($sqlQuery);
// JavaScript code to populate the DropDown.
echo "<select name='". $dropdownControlName ."'>";
echo "<option>Select</option>";
while($row=mysql_fetch_array($result))
{
echo "<option value=<?=". $row[$idColumnName] ."?>><?=". $row[$displayColumnName] ."?></option>";
}
echo "</select>";
dbconnection::CloseConnection();
?>
I believe the javascript is the source of the problem. Let me explain:
The function HandleResponse() always fills in the same ID. The variable DropDownName from your MakeRequest() function isn't passed anywhere to your HandlResponse() function. Try to add this argument, it should work better.
Apart from that, using MySQL queries directly inside your javascript is a big security issue.
1) You tell people the inner structure of your database.
2) People can modify this request to retrieve anything they want! FROM your database!
NEVER user directly user input (and yes, the GET argument CAN be user input: it's a simple GET variable, everyone has access to it).
I once used javascript to generate a query string, but was able to leave off many important details such as table name and WHERE conditions. I also made sure to use mysql_real_escape_string on it, adding strings to the front and back server side to make a complete query string. It was much easier than trying to post arrays. I feel that this was a safe and easier alternative.

Categories