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.
Related
I'm beginning to work with AJAX, and I'm struggling with the next few things.
I'm working in Wordpress, with custom tables.
By the way, that's why the global $wpdb is there.
First, I have a Select, when you choose an option, the ID value will get stored in a variable in jQuery. This is done by the
onchange="selectRequest(this)"
global $wpdb;
$Estado = $wpdb->get_results("SELECT * FROM cor_estado;");
?>
<p>Busqueda por Estado</p>
<select class="select" id="estado" name="estado" value="" type="text" onchange="selectRequest(this);">
<option value="" disabled selected>Seleccione un estado...</option>
<?php
foreach ($Estado as $Estados ) {
echo "<option value='".$Estados->estado_id."' type='text'>".$Estados->nombre_estado."</option>";
}
?>
</select>
The Select will fill up with the id on value and the name.
This is my jQuery, but I'm having a problem here, if I leave everything on the jQuery(document).ready(){CODE HERE}, the Function selectRequest(id), won't work at all, I don't know if that has anything to do with the way that I am getting the id from the select.
Here it changed, now I am trying to receive HTML, I created the complete table on "table.php", and now I am trying to get it back
<script type="text/javascript">
function selectRequest(id){ // id of select
var selectVal = jQuery(id).val(); // currently selected
selectVal = selectVal.toString();
alert(selectVal);
jQuery.ajax({
type:"POST",
url:"<?php echo get_template_directory_uri(); ?>/table.php",
dataType: "html",
data:{selectVal:selectVal},
success:function(resultHtml){
jQuery("#resultado").html(resultHtml);
},
error:function(resultHtml){
alert("What follows is blank: " + data);
}
});
}
</script>
my PHP is like this at the moment, one big change was in the WHERE, since I am using an INNER JOIN, I needed to specify on which table the "estado_id" was going to be, since Wordpress uses table prefix, it was necessary to add it in this place too.
Like I said before, I decided to build the table here, and send it to AJAX with an echo, I created $table, and each time something was created inside the table, I added it with ".=".
Testing this inside the table.php without the "If(isset($_post['selectVal']))", and having an static ID it worked on the table.php document, but if I echo $table, I get nothing on AJAX, it appears as blank.
<?php
//table.php
global $wpdb;
if(isset($_POST["selectVal"])){
$Estado_id = $_POST["selectVal"];
$Estado = $wpdb->get_results("SELECT * FROM cor_municipio INNER JOIN cor_estado ON cor_municipio.estado_id = cor_estado.estado_id WHERE cor_estado.estado_id = $Estado_id;");
$table = "<table>";
$table .="<thead>";
$table .="<tr>";
$table .="<th>Municipio</th>";
$table .="<th>Estado</th>";
$table .="</tr>";
$table .="</thead>";
$table .="<tbody>";
foreach ($Estado as $row) {
$table .="<tr>";
$table .="<td>".$row->nombre_municipio."</td>";
$table .="<td>".$row->nombre_estado."</td>";
$table .="</tr>";
}
$table .="</tbody>";
$table .="</table>";
echo $table;
}
?>
This is the HTML div where I want to display the echo $table content. At the moment if I select an option, the only thing that happens is that the P element disappears.
<div id="resultado">
<p>Estado Seleccionado</p>
</div>
The new problem is receiving this echo $table and displaying it where AJAX receives it.
instead of receiving data in JSON format, use HTML formatted data & replace your data directly in table. Using that your base issue "the amount of information in them will be different on each select option" will be resolved.
There's not a fixed rule... Sometimes is faster to create the html in the php and return it formatted so you can show it directly and sometimes is better to return raw data and handle it in javascript/jquery.
If the data you get from the ajax request is just for showing and you don't need to modify anything that depends of other elements in your current view, I will format the html response directly in the php. If you need to change something, then maybe I will go with JSON.
In your ajax request you establish JSON as the data format, so the response in your PHP has to be JSON. You almost have it. Uncomment the foreach but instead of independent variables ($info1, $info2) create an array with the fields you need for your response, and set key names. For example...
$response = array();
foreach ($Estado as $row) {
$response['municipio'] = $row->nombre_municipio;
$response['estado'] = $row->nombre_estado;
.....
}
Once you have the array created, convert it to JSON and return with...
print_r(json_encode($response));
Then, in your jquery ajax success function you can access each field with...
data.municipio or data['municipio']
data.estado or data['estado']
...
I hope it helps
So, the basic problem here was that I was following the steps to do this using the tools (JS, PHP, HTML and CSS) outside the Wordpress environment, this was the issue. I'm still solving some aspects about my AJAX request, I will try to update this answer as fast as I can.
In this Wordpress Codex entry, they explain it in detail.
Basically Wordpress has it's own way of using AJAX, so no matter if this 'looked' correct to me, the Wordpress site wasn't going to display anything from it.
Here is the solution that I used to solve my problem.
<!-- language: lang-js -->
UPDATED CODE
jQuery(document).ready(function() {
jQuery('#estado').change(function() {
var selectVal = jQuery('option:selected').val();
selectVal = selectVal.toString();
jQuery.ajax({
url:"/cors/wp-admin/admin-ajax.php",
type:"POST",
data:{action:'my_action', selectVal: selectVal},
success:function(data){
jQuery("#municipio_result").hide(500);
jQuery("#municipio_result").removeData();
jQuery("#municipio_result").html(data);
jQuery("#municipio_result").show(500);
},
});
});
});
STEP #1
/wp-admin/admin-ajax.php //will be the URL for all your custom AJAX requests.
This is absolutely necessary, because this document verifies the AJAX 'actions', and points them to your functions.php
STEP #2
data:{action:'your_action_name', val1: 1, val2: 2 ...}
The first variable that you have to send will always be action, the value can be the anything you want.
As I said earlier, admin-ajax.php looks for the variable action when it receives an AJAX request from any file, it will look for action, once it finds it, it will redirect it to the functions.php file located inside your_theme folder.
STEP #3
Inside you functions.php file, you will add the PHP code as a function, like this:
<!-- language: lang-sql -->
function selectEstado(){
global $wpdb;
if(isset($_POST["selectVal"])){
$Estado_id = $_POST["selectVal"];
$Estado = $wpdb->get_results("SELECT * FROM cor_municipio INNER JOIN cor_estado ON cor_municipio.estado_id = cor_estado.estado_id WHERE cor_estado.estado_id = $Estado_id;");
$table = "<table>";
$table .="<thead>";
$table .="<tr>";
$table .="<th>Municipio</th>";
$table .="<th>Estado</th>";
$table .="</tr>";
$table .="</thead>";
$table .="<tbody>";
foreach ($Estado as $row) {
$table .="<tr>";
$table .="<td>".$row->nombre_municipio."</td>";
$table .="<td>".$row->nombre_estado."</td>";
$table .="</tr>";
}
$table .="</tbody>";
$table .="</table>";
echo $table;
wp_die();
}
}
add_action('wp_ajax_my_action', 'selectEstado');
add_action('wp_ajax_nopriv_my_action', 'selectEstado');
STEP #4
Inside your functions.php file you will create a function, can be called whatever you want, for example 'your_function_name'.
To access easily to the database, Wordpress uses the variable $wpdb, by including the line like this global $wpdb; now you can use it to access the database without any problems.
Now you have to check if the values after action got there, the if(isset($_POST)) will take care of it. To check the Database, you use the $wpdb->get_result("");
Basically what I am doing with the INNER JOIN, is checking a column name, and checking where the two tables match, and then pulling the rest of the columns that the element on the table has in "cor_municipio" and "cor_estado".
(In this code I am using JOINS, if you want to know more about them, I'll leave a link below)
Here they explain JOINS with Venn diagrams
Then I created a variable that each time a part of the table was created, it was being added to it.
You echo your data, and don't forget "wp_die();"
STEP #5
This is the last part to have your AJAX request working on Wordpress.
The next two lines are very important for it to work, this is the action that admin-ajax.php is looking for, and it's here that it references it's value, these lines look like this for every new AJAX request you need to make:
add_action('wp_ajax_', '');
add_action('wp_ajax_nopriv_', '');
this is the "default" way the lines are written, but you will need to complete them with two things.
The action value you used in the AJAX request, in my case is 'my_action', or in this example 'your_action_name'.
The second value is the name of the function created inside your functions.php file.
It will end up looking like this for me:
add_action('wp_ajax_my_action', 'selectEstado');
add_action('wp_ajax_nopriv_my_action', 'selectEstado');
Using the value of 'your_action_name' and 'your_function_name':
add_action('wp_ajax_your_action_name', 'your_function_name');
add_action('wp_ajax_nopriv_your_action_name', 'your_function_name');
The first line is for logged in users, and the second one is for visitors, if you want to display something different for logged in users and another one for visitors, you will need to create a function for each of them, and just use one attribute.
add_action('wp_ajax_your_action_name', 'your_function_name1'); // for registered users
add_action('wp_ajax_nopriv_your_action_name', 'your_function_name2'); // for visitors
Again, this is PHP code written in admin-ajax.php, if you want to look deeper into it.
I already found out my problem, when I was sending the data on the first time I was using:
data:{action:'my_action', selectVal: 'selectVal'},
Basically what I was sending to Wordpress on selectVal, was the string
selectVal
So when my function tried to find the id based on the receiving data, it wasn't going to find anything, because it was a string with those letter.
SOLUTION
jQuery(document).ready(function() {
jQuery('#estado').change(function() {
var selectVal = jQuery('option:selected').val();
selectVal = selectVal.toString();
jQuery.ajax({
url:"/cors/wp-admin/admin-ajax.php",
type:"POST",
data:{action:'my_action', selectVal: selectVal}, // The right way to send it
success:function(data){
jQuery("#municipio_result").hide(500);
jQuery("#municipio_result").removeData();
jQuery("#municipio_result").html(data);
jQuery("#municipio_result").show(500);
},
});
});
});
What I am sending now is the value, and now my AJAX success:function, receives the complete table, I also changed the jQuery code, because in the first example, when adding ".hide() or .show()", it was sending multiple errors.
To add conditions by user role you can edit the admin-ajax.php to make it simpler for all the AJAX requests.
I know is way too long, but if you were having some trouble, I wanted to explain all the different elements that are used, to make it easier to understand what is happening with AJAX in Wordpress.
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.
I've found most of the pieces i've needed for this form (making the fields dynamic, etc.) however now the array part of this doesn't seem to work to be able to submit correctly.
what i'm trying to accomplish:
a form with a select field that can be duplicated dynamically and then be submitted as a part of the form to it's own table. so if we add and choose three people in the one form, it submits to it's own attending table with a foreign key back to the event the form is for. had to make it dynamic because we'll never know for sure how many people will be attending said event, but it has to happen all in one form. just because it does. my boss says so.
here's my javascript for the add another field button:
$(document).ready(function() {
$('#btnAdd').click(function() {
var num = $('.clonedInput').length; // how many "duplicatable" input fields we currently have
var newNum = new Number(num + 1); // the numeric ID of the new input field being added
// create the new element via clone(), and manipulate it's ID using newNum value
var newElem = $('#input' + num).clone().attr('id', 'input' + newNum);
// manipulate the id value of the input inside the new element
newElem.children(':first').attr('id', 'attendee' + newNum).attr('name', 'attendee[' + newNum + ']');
// insert the new element after the last "duplicatable" input field
$('#input' + num).after(newElem);
// enable the "remove" button
$('#btnDel').attr('disabled','');
// business rule: you can only add 5 names
if (newNum == 6)
$('#btnAdd').attr('disabled','disabled');
});
here's what the field starts out as in the form:
<div id="input1" style="margin-bottom:4px;" class="clonedInput">
<select name="attendee[1]" id="attendee1" style='float:right;margin-right:4.5%;'>
<option value=''>Please choose one...</option>
<?php
while($row_attendees = mysql_fetch_assoc($res_attendees)){
$attendee_id = $row_attendees['attendee_id'];
$attendee_name = $row_attendees['name'];
echo "<option value='".$attendee_id."'>".$attendee_name." </option>";
}
?>
</select><label style='width:100px;display:inline-block;line-height:28px;' for="attendee">Attendee</label>
</div>
I'm getting all the things to change correctly. all of the select inputs are being id'd and name'd correctly. the div is being updated the same. all of that works correctly. what doesn't is when i go to submit. here's my php:
foreach($_POST['attendee'] as $attendee){
$sql_attendees = "INSERT into marketing_calendar.attending (event_title, attendee_id) VALUES ('".$_POST['title']."','".$attendee."')";
$res_attendees = mysql_query($sql_attendees) or die(mysql_error());
}
all the tutorials i used to pull this together show this as correct. however it doesn't work. i'm only getting whatever the first dropdown is, and nothing else is populating into the array. at least that's all it shows/submits if i run the form or echo the attendee variable in the foreach statement. PLEASE HELP! :)
thanks a ton in advance.
UPDATE
I have tried a few ways discussed with another user to display the array for $_POST['attendee'], however it still just shows 1 id in the array, and not however many fields i've actually added. I've also tried removing the number from the array in the select's name attribute. so it would just be name='attendee[]' instead of name='attendee[1]' and so on. this also doesn't help any. can someone please help with why my dynamically added fields aren't being added to the array?
I put your code into a JSfiddle, here: http://jsfiddle.net/rv8Mv/1/
It looks like the selects are being added correctly. You can check by clicking the "Submit" button, which shows a data string of what will be submitted to the server.
One thing you might want to check, is to make sure you are enclosing all the select elements inside a <form> element, which you didn't include in your question.
I think your problem is in the PHP code on the server.
On the server, make sure you are receiving all the variables by using this code:
<?php
foreach($_POST as $key => $value){
error_log($key.' -> '.$value;
}
?>
Then check your error log to see the names and values for all the POST variables.
You are probably not referencing the POST variables correctly in your current PHP code.
You should change your sql to look like this:
foreach($_POST['attendee'] as $attendee){
$sql_attendees = "INSERT into marketing_calendar.attending (event_title, attendee_id) VALUES ('".$_POST['title']."',".$attendee.")";
$res_attendees = mysql_query($sql_attendees) or die(mysql_error());
}
Your attendee_id is an int column. You were wrapping the column content with single quotes, which denotes a string. This would result in your attendee_id being null if your column is defined as nullable.
Have been looking around for a solution to this and have found some help on stack overflow but in most cases the examples I have found are not using arrays formed from a database query. Here is some code for what I am trying to achieve...
$stores = mysql_query("SELECT * FROM Stores");
$staff = mysql_query("SELECT * FROM Staff");
I would like to create two elements, one for stores and another for staff but I want to filter the staff based on the store client side. So if the user selects "Sydney" from the first dropdown, they are presented with only staff that work at the Sydney store in the second dropdown. Then if the user chooses "London" from the first dropdown, the Sydney staff are replaced by the London staff and so on.
My server side scripting is done with PHP and I am able to create the two dropdowns with PHP. But I am stuck on the jQuery to remove the I don't want from the second dropdown.
I know this is possible, because I see it used all the time. I have seen lots of examples of how to manage this but none of the examples use data from the PHP array to insert the .
You need ajax.
When the user selects something in a dropdown, this fires an event that you can process. Inside of this process you take the value of the selection like jQuery('#id_dropdown').val(), and send this via ajax (I like using POST since you dont run into GET request size limits).
You process this on the server side with php, accessing to the database with the value selected and sent via ajax. When you have the right results for the second dropdown you can output it via echo.
Finally, when the response is returned to jQuery, you can insert all the options in the new dropdown.
JAVASCRIPT PART:
Bind event to the first dropdown
Get value of the option selected in the dropdown
Make ajax request
Here is some example code:
var parameters='value_selected='+value_dropdown;
jQuery.Post({
url: '/destiny_when_I_process',
data: parameters,
success: func_callback
});
//here you can imagine a pause, because PHP is processing the data you send by post
//....
//....
//this part is executed when php send the information
function func_callback(response_from_php){
jQuery('#second_dropdown').html(response_from_php);
}
PHP PART:
get value from POST
access database using this value
echo (send response). You send a chain of text (in HTML), really this is not very professional, but is OK for demonstration purposes. Professionals send JSON, since JSON is lighter-weight.
JAVASCRIPT PART (SECOND PART)
in the callback function, you receive the response data via the first parameter
Insert new data in the second dropdown (since the data is already HTML, you do not need to process it)
for the secondary drop down, yes, you'll need some ajax.
You can create a script that go fetch the result coresponding to the store and send back the option listm witch is inserted in the ooption.
Using jquery and php you'll need a few thing.
A php file to get the result and return the options. (let say getStaff.php)
<?php
//get the store id by post is it is set
if (isset($_POST['store->id']) $store_id = mysqli_real_escape_string($_POST['store_id']);
//get the data !! notice the WHERE caluse
$r = mysql_query("SELECT * FROM Staff" *WHERE store=''$store->is*);
//split the data in the array
$staffs=array();
while ($assoc = mysql_fetch_assoc($r)) {
//Varialbe = $assoc['colum_name'];
$staff->id=$assoc['id'];
$staff->name=$assoc['name'];
//and so on for each colum in your table.
array_push($staffs, $assoc);
}
//echo the result as option
foreach ($staffs as $staff) echo "<option value='$staff->id'>$staff->name</option>";
?>
In you first select, add
onchange="$.post('getStaff.php', {store_id:$(this).val()}, function (data){ $('#staff_select').html(data);});"
and add an id to your second select (staff_select) in this ecample.
As an explanation: When the 1st dropdown change, it send a request to getStaff.php with the store_id as a POST argument. The php sript get the syaff according to the store Id and bring back a list of option tags for your secondary select. Than jquery add the 'data' to your secondary select and VOilĂ !
Hope tih sis clear cause it's a bunch of little thing together that will make it work. Sorry if it's seems sloppy as an answer but it's really simple once you know it.
Spent the afternoon learning how to do this and it's working quite well. Posted the new code here for others....
Thanks to http://forum.codecall.net/topic/59341-php-sql-jquery-and-ajax-populate-select-boxes/ for the tutorial.
And thanks to everyone here.
PHP to build for the first :
function agency_select() {
include('../include/dbase.php');
$agencies = $pdo->query("SELECT * FROM agency WHERE Status='active' ORDER BY AgencyName");
$opt = '';
while ($age_array = $agencies->fetch(PDO::FETCH_ASSOC)) {
$opt .= '<option value="'.$age_array['AgencyId'].'">'.$age_array['AgencyId'].' - '.$age_array['AgencyName'].' - '.$age_array['AgencySuburb'].'</option>'."\n\t\t\t\t\t\t\t";
}
return $opt;
}
HTML for the two elements:
<label for="AgencyId">Client/Agency:</label>
<select class="uniform" id="AgencyId" name="AgencyId" style="width: 400px; overflow-x: hidden">
<?php echo agency_select(); ?>
</select>
<label for="Contact">Contact: </label>
<select class="uniform" id="Contact" name="Contact" style="width: 300px; overflow-x: hidden">
<option value="">----Select Client/Agency----</option>
</select>
AJAX file:
if(isset($_POST['AgencyId'])) {
include('../include/dbase.php');
$option = '<option value="">----Select Contact----</option>';
$query = $pdo->prepare("SELECT * FROM client WHERE AgencyId= ? AND Status='active' ORDER BY FirstName");
$result = $query->execute(array($_POST['AgencyId'])));
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
$option .= '<option value="'.$row['id'].'">'.$row['FirstName'].' '.$row['LastName'].'</option>';
}
echo $option;
}
jQuery:
$(document).ready(function () {
update_contacts();
});
function update_contacts() {
$('#AgencyId').change(function() {
$('#Contact').fadeOut();
$('#loader').show();
$.post('../ajax/ajax_contact_select.php', {
AgencyId: $('#AgencyId').val()
}, function (response) {
setTimeout("finishajax('Contact', '"+escape(response)+"')", 400);
});
return false;
});
}
function finishajax(id,response) {
$('#loader').hide();
$('#'+id).html(unescape(response));
$('#'+id).fadeIn();
}
i'll try to help you as much as i can a explain it.
mysql_query, you sould use mysqli btw, mtsql being decrecated, return a result set.
This means you will have all the records from your query. You need to brak down your result into before you can work with it. This is done by using methids like mysql_fetch_assoc, mysql_fetch_row, etc. There something like fetch to array to but i don't master it so i will use fetch assoc, for this reply.
So once you have yoru result set, $stores & $staff in your case, you then call a while loop on your results to get th data as in:
while ($assoc = mysql_fetch_assoc($r)) {
//Varialbe = $assoc['colum_name'];
$stores->id=$assoc['id'];
$stores->name=$assoc['name'];
//and so on for each colum in your table.
array_push($stores, $assoc);
}
Then you can export it as you want.
in you case would be something like
foreach ($stores as $store) echo "<option value='$store->id'>$store->name</option>";
I storngly suggest you take alook at http://php.net/manual/en/function.mysql-fetch-array.php witch will do the same a fetch_assoc bu with an array with the columname as key.
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())