Populating drop downs with MySQL entries - javascript

I have a MySQL database that contains, amongst other things, 2 tables. One is the events table, containing event names and other details. The other is the instance table. This table links the events table to a venue table and adds a date, so each row is an instance of the linked event.
I am making an event booking form for internal use for these events. I want to allow selection of the event to be booked via a dropdown list. So, I have populated one dropdown with the event names:
$qEvent = "SELECT event_name, event_id FROM events";
$rEvent = mysqli_query($dbc,$qEvent);
echo '<select>';
while ($row = mysqli_fetch_assoc($rEvent)) {
echo '<option value="'.$row['event_id'].'">'.$row['event_name'].'</option>';
}
echo '</select>';
What I now want to do is, for the selected event, grab all the instances associated with that event, and populate another dropdown with the dates.
Can I do this with PHP, or do I need to dip into Javascript? I think I just need some way to grab the event_id value of the dropdown selection and then query based on that, but I don't know how without Javascript.

You should be looking at Javascript or jQuery for achieving your goal. I've used jQuery based on my question to you earlier. It's also simpler and less code.
Your PHP:
Add an ID attribute event_menu to your select menu
echo '<select id="event_menu">';
while ($row = mysqli_fetch_assoc($rEvent)) {
echo '<option value="'.$row['event_id'].'">'.$row['event_name'].'</option>';
}
echo '</select>';
<div id="container_for_new_menu"></div>
Using jQuery:
$('#event_menu').on('change', function() {
// get selected value and build data string for AJAX
var event_selected = "event_selected="+$(this).val();
// send the selected data to a PHP page to build the populated menu
$.ajax({
url : 'populate-menu.php',
type: 'POST',
data : event_selected,
dataType : 'html',
success : function(data) {
$('#container_for_new_menu').html(data);
}, error : function() {
alert("Something went wrong!");
}
});
});
On populate-menu.php, have something like:
$event_selected = isset($_POST['event_selected']) ? $_POST['event_selected'] : null;
// do SQL query here based on user's selection
// making sure you validate the data in the POST request for malicious BS
// or use parameterized queries
// then build a new menu to send back
echo '<select>';
// loop through results and build options
echo '</select>';
This new menu will then be posted back to your original page into the container_for_new_menu element.

By the looks of it, you want to populate the "instances" dropdown based on the selection the user makes on the "event" dropdown. You cannot do this without Javascript.
My suggested way of doing this is to use AJAX to pull the instance data and populate the "instances" dropdown on change of the "event" dropdown. Useful resources below for simple AJAX get with jQuery:
http://api.jquery.com/jQuery.get/
http://remysharp.com/2007/01/20/auto-populating-select-boxes-using-jquery-ajax/

You need some kind of Javascript to accomplish this. Either:
Basic- submit the form on select and let php populate the instance drop-down.
More elegant- use Javascript to make an Ajax call on select which will dynamically replace the instance drop-down's div.

You will need JavaScript to populate the second drop down box. I suggest you load all the values into JSON on the page and then you can just use a jQuery on change event to populate the second select box.

Related

Populate Select element with Jquery and AJAX and without async:false attribute

I am trying to populate a select element from database, I need to pass some variable from my Jquery script first (id of a button). For this purpose I used AJAX call and passed variables to PHP file, made SQL query, fetched data... Everything turned out to be fine... but when I created html code and then passed from PHP to AJAX. The Jquery variable html was not taking any data from AJAX call... Then I read about using async:false attribute within AJAX call.. But I know it is not a good solution... I am new to web development.. I want you to suggest me what should I do...
Example of my code is as below
'''
<span id="span_product_details"></span>
<script type="text/javascript">
$(document).ready(function(){
var v1=1; //actually id of a button will be saved in this variable which is necessary to make database query
var v2=2;
var v3=3;
var html='';
html += '<select name="abc" id="abc" class="form-control selectpicker" data-live-search="true" required>';
$.ajax({
url:"practice.php",
method:"POST",
data:{v1:v1,v2:v3,v3:v3},
dataType:"html",
success:function(data)
{
html += data;
}
});
html += '</select>';
$('#span_product_details').append(html);
$('.selectpicker').selectpicker();
});
</script>
<?php
//example code of practice.php file (a seperate file)
//$query = (based on $_POST['v1'], $_POST['v2'] and $_POST['v3'])
$str='<option value="1">Hello</option>'; //data obtained from database
$str.='<option value="2">Hi</option>'; //data obtained from database
echo $str;
?>
'''
For more detailed understanding I am explaining the problem with more details..
I have a table each row of that table has 4 columns,
ProcessID, ProcessDate, Edit_btn, Delete_btn
during each process multiple parts were processed lets say part No. A1, A2, A3
ID of Edit button is also same as ProcessID.
Now When Edit button is pressed, a modal will open, an AJAX call is performed and that modal shows
rows with data as follows,
(select element with Part number) (part status accepted, rejected etc) (remarks)
Now while Editing user must be able to add more parts to the same process... For this purpose there is an (Add button)
With first row of modal,
Now When Add button is pressed, a new row will be added to the modal,
that row must have a select element which should be populated with a list of already processed parts
and parts which were not processed...
For this purpose I had to make an AJAX call, which will pass the EDIT_BTN id (to fetch already processed parts under this.processID)
to php file,
And get the options for select element. During this operation I am having the above stated issues...
One way is to use async:false which will work.
the other way is to append basic html first, the load data
or you can just write your select html in modal and on modal show event, load data,
p.s. data v1,v2,v3 you use it your way, i just outlined the solution,
$(document).ready(function(){
var v1=1; //actually id of a button will be saved in this variable which is necessary to make database query
var v2=2;
var v3=3;
var html='';
html += '<select name="abc" id="abc" class="form-control selectpicker" data-live-search="true" required>';
html += '</select>';
$('#span_product_details').append(html);
load_dropdown(v1,v2,v3);
}
// use v1,v2,v3 however you have, either in function or global, param, or any other way
function load_dropdown(v1,v2,v3) {
$.ajax({
url:"practice.php",
method:"POST",
data:{v1:v1,v2:v3,v3:v3},
success:function(data)
{
console.log(data); // if in console it display html then fine,else check format
$('#abc').append(data); // or use .selectpicker as selector if its unique
$('.selectpicker').selectpicker();
}
});
}

How to update a table without changing the onscreen data displayed

I need to display a simple list of hundreds of items which are on a MySQL table, review the list onscreen and click on a link beside each unwanted item to delete it from the table. This is an internal management procedure; no outside user is involved. I do not need the item to disappear from the list immediately; I will refresh the list periodically so items deleted from the table are no longer listed. I do not need any message to confirm that the item has been deleted. The important thing is that I don't want to lose sight of the list each time I delete an item and have to click on a "go back" button to return to the list.
The table uses MySQL. All my coding to date has been in PHP. So I am using php to display the list of items, on a non-html screen. This is the code for each item:
echo $item." <a href='item_delete.php?id=".$item."'>Delete item</a><br />";
This is the code for item_delete.php:
<?php
require ('connect.php'); // To define connection $con
$id = $_POST['id'];
mysqli_query($con, "DELETE FROM `items_table` WHERE `id` = $id");
?>
The item is deleted correctly but a blank screen is (understandably) displayed.
I have done a lot of searching but most people needing help want to do more advanced things and - because I have so far managed to avoid learning JavaScript, jQuery and AJAX - I can't even work out which of those technologies I need to update a table without changing the screen.
I get the impression that each PHP script always takes "focus" with it, so maybe I need a little JavaScript script to do this ?
If so:
- can I just change item_delete.php to item_delete.js or do I have to define the non-html list as an html one ?
- what js code is needed in item_delete.js ?
I have read about using: header("location:javascript://history.go(-1)");
or: header('Location: ' . $_SERVER['HTTP_REFERER']);
but they don't go back to the onscreen list.
I don't think I want the js script to perform a virtual "go back" because the list is originally produced by using (about 20) $_POST parameters, so I still seem to have to refresh it each time.
So I'd like a solution to remain with the list - rather than leave it and return to it. Thanks.
It would make a lot of sense to do the deletion asynchronously using javascript. However, the simplest and messiest way to achieve what you want, is to add target="_blank" to the links, (which will leave you with a open blank tab for each delete request you do).
echo $item." <a href='item_delete.php?id=".$item."' target='_blank'>Delete item</a><br />";
Or you can solve it by adding checkboxes in front of every item, check the items you want to delete and submit them as form parameters to the delete script.
If you want to delete to row in the onscreen table after the actual PHP code has run you can use the following implementation:
The HTML structure for the link requires a unique class name, such as:
echo 'Delete item'
Note the item id is stored inside a HTML5 data attribute. I have also added an onclick event handler which returns false to avoid the link refreshing the page.
The javascript used to delete the item use the JQuery AJAX method and binds to the specified class, which is: item-delete. The implementation requires Jquery version >= 1.9.0
(function(){
$('.item-delete').click(function(event) {
var target = $(event.target);
var id = target.data('item-id');
$.ajax({
url: 'item_delete.php',
method: 'POST',
data: {
id: id
},
}).done(function() {
target.remove();
}).error(function(err) {
console.error('Could not delete item with ID: ' + id);
console.error(err);
});
});
}())
The event listener is defined inside a self-executing function, which is automatically executed when the page-load completes and avoids poluting the global namespace.
You can delete the item directly on the same page without moving to another
page by passing the id through a hyperlink and then get it to finally delete
the unwanted item. CHECK THIS OUT, and please let me whether or not is what you
wanted :-)
// connection
mysql_connect("host", "user", "password");
mysql_select_db("your database name");
// select all the items from table.
$selectQuery = mysql_query("SELECT * FROM table_name" );
// use while loop to list all the items...
while( $row = mysql_fetch_array($selectQuery) )
{
// list the items as a hyperlink, passing their id through the URL.
?>
<?php echo "delete " . $row["item_name"]; ?>
<?php
}
// Below is the code to delete the item.
if( isset( $_GET["id"] ) )
{
$itemId = $_GET["id"];
// query to delete item
$deleteQuery = mysql_query("DELETE FROM table_name WHERE id = '$itemId' ");
//-----------THE MOST IMPORTANT PART. >>>
// redirect if delete is successfull.
if( $deleteQuery )
{
// reload the page to get the items minus the deleted one...
// let's say your sript name is delete.php
header("Location:delete.php");
}
}
?>
</code>

Dropdown values disappear in an AJAX-based jQuery element

I am growing quite fond using AJAX, JSON, and jQuery. I am coding from scratch an application to replace a previous application that is flawed.
Although I am progressing and getting better using the AJAX method, I am coming across various issues that I want to correct, so that my replacement application is flawless.
My application uses AJAX to call PHP scripts. It returns JSON that I use to populate certain dropdowns for the user to select.
For the most part, the application does what it is supposed to do. The many dropdowns populate with the parsed JSON data. The user can select 1 or more dropdowns which will then fire a SEARCH query that will return data.
The issue appears to happen when the data-set from the previous search is large. I'm talking barely thousands. When I click on the dropdown to conduct a new search, the dropdown (that was previously populating the JSON data) is now blank.
It doesn't do it all the time. It seems this issue arises when the initial search returns a large data set. I cannot be for sure.
Here is the html within my file called bpSearch.php: (just two of my dropdowns)
<div class="input-group">
<span class="input-group-addon">Sales Rep</span>
<select class="form-control" id="salesRep" name="salesRep">
<option value=""></option>
</select>
</div>
<div class="input-group">
<span class="input-group-addon">Services</span>
<select class="form-control" id="service" name="service">
<option value=""></option>
</select>
</div>
There are a few more dropdowns. I only listed 2.
Here is the javascript (also within the same file, bpSearch.php) that populates the dropdowns via AJAX and JSON:
<script type="text/javascript">
// populates the dropdown id #salesRep
$.getJSON( "api/reps.php", function( data )
{
$.each(data, function(index, item)
{
$('<option>').
attr('value', item.fullname).
text(item.fullname).
appendTo($('#salesRep'));
});
});
// populates the dropdown id #service
$.getJSON( "api/services.php", function( data )
{
$.each(data, function(index, item)
{
$('<option>').
attr('value', item.service).
text(item.service).
appendTo($('#service'));
});
});
</script>
Here is the PHP called reps.php. This returns the JSON data for the #service dropdown:
<?php
if ($result =
mysqli_query($dbc, "SELECT DISTINCT(service)
FROM services_imp ORDER BY service"))
{
$out = array();
while ($row = $result->fetch_assoc())
{
$out[] = $row;
}
echo json_encode($out);
mysqli_free_result($result);
}
?>
At this point, I don't think I need to show the code for reps.php. It pretty much looks exactly the same as the code for services.php, except of course for the names of the fields that I search in the query.
With all the code above, I can populate the dropdowns as stated. But, as I also previously stated, sometimes the dropdown values disappear after conducting a search. This seems to always happen when the data-set is large.
Here is what the services dropdown looks like when it is working:
And here is what it looks like after I conduct a search that returns a larger data-set:
I do not understand why this is happening. What might be causing it?
It is a good practice to ensure that the dropdowns are loaded in DOM ready event
$(function()
{
//AJAX call for loading dropdowns
})
Please make sure first that the calls are made in DOM ready event.
The following code disables the dropdown when the AJAX function is called and enables it when the data is fully loaded. Execution starts when the page is fully loaded and I reduced your AJAX calls to one generic function that accepts an element and a uri as input. This function also makes a clone of the select. Appending the new options in memory and when the list is build the original select is replaced with the cloned one. This should enhance the browser performance.
function loadDataAndAppendToSelect(select, uri)
{
$(select).prop('disabled', true); //disable
// populates the dropdown id
$.getJSON( uri, function( data )
{
var tempElement = $(select).clone();
$.each(data, function(index, item)
{
$('<option>').
attr('value', item.fullname).
text(item.fullname).
appendTo(tempElement);
});
$(select).replaceWith(tempElement);
$(select).prop('disabled', false); //enable
});
}
$(document).ready(function(){
loadDataAndAppendToSelect('#salesRep', 'api/reps.php');
loadDataAndAppendToSelect('#service', 'api/services.php');
});

how to get current selected from <select> and on every change in selected

i was trying to make a dynamic where the selected option was supposed to be caught in a variable for php as i would use it as a condition to be put in a where clause for mysql. and when a user selects another option the of another tag would change
<form method="GET" action="">
<select name="docSpec" id="docSpec">
<?php
$docSpecQuery = "select DISTINCT specialty from doctors"; // i was going to put a where condition here so i could only project names of the doctor with the selected specialty.
$docquery = "select doctorName from doctors";
$docSpec = mysqli_query($conn,$docSpecQuery);
$docresult = mysqli_query($conn,$docquery);
//this php block is for my options, i used a loop
while ($row = mysqli_fetch_row($docSpec))
{
echo "<option value='$row[0]'>$row[0]</option>";
}
unset($row);
?>
</select>
<script type="text/javascript">
$('#docSpec').on("change",function(){
var option = $("option:selected",this).val();
alert(option);
});
</script>
</form>
i hope i was clear enough i will be waiting if you want to clarify some things in my code.
tell me if you need another parts of my code. please i need help
PHP is executed on the server, which means that by the time you print the <select> you run the jQuery code you can't affect the mysql query directly. You can however move the query to another script, and target it with an ajax call that returns the select and options or, ideally, the dataset so you can create it programmatically.
Your php script will do the same as it does right now but fetch the value from the url for the conditional query. For instance, you could have this php at mysite.com/select.php and pass the variable gynecologist like so mysite.com/select.php?spec=gynecologist then read it with $_GET['spec'] and use it in the query.
In your javascript, you'll get that html by calling something like:
$('#docSpec').on("change",function(){
$.get( "mysite.com/select.php?spec="+$(this).find("option:selected"),
function( data ) {
//data contains the output for the php file, update the dom
//with it or whatever
});
});

Populating JScript Array for reuse on SELECTs

Forgive me if this is already 'somewhere' on StackOverflow, but I don't 100% know exactly what it would come under...
I'm trying to retrieve information from a WebService, store this in an array, and then for each <select> within my ASP.Net Datalist, populate it with the array AND have binding attached to an OnChange event.
In other words, I have an array which contains "Yes, No, Maybe"
I've an ASP.Net Datalist with ten items, therefore I'd have 10 <Select>s each one having "Yes, No, Maybe" as a selectable item.
When the user changes one of those <Select>s, an event is fired for me to write back to the database.
I know I can use the [ID=^ but don't know how to:
a) Get the page to populate the <Select> as it's created with the array
b) Assign a Change function per <Select> so I can write back (the writing back I can do easy, it's just binding the event).
Any thoughts on this?
I have built a simple example that demonstrates, I think, what you are attempting to accomplish. I don't have an ASP.Net server for building examples, so I have instead used Yahoo's YQL to simulate the remote datasource you would be getting from your server.
Example page => http://mikegrace.s3.amazonaws.com/forums/stack-overflow/example-multiple-selects-from-datasource.html
Example steps:
query datasource to get array of select questions
build HTML of selects
append HTML to page
attach change event listener to selects
on select value change submit value
Example jQuery:
// get list of questions
$.ajax({
url: url,
dataType: "jsonp",
success: function(data) {
// build string of HTML of selects to append to page
var selectHtml = "";
$(data.query.results.p).each(function(index, element) {
selectHtml += '<select class="auto" name="question'+index+'"><option value="Yes">Yes</option><option value="No">No</option><option value="Maybe">Maybe</option></select> '+element+'<br/>';
});
// append HTML to page
$(document.body).append(selectHtml);
// bind change event to submit data
$("select.auto").change(function() {
var name = $(this).attr("name");
var val = $(this).val();
// replace the following with real submit code
$(document.body).append("<p>Submitting "+name+" with value of "+val+"</p>");
});
}
});
Example datasource => http://mikegrace.s3.amazonaws.com/forums/stack-overflow/example-multiple-selects-from-datasource-datasource.html
Example loaded:
Example select value changed:

Categories

Resources