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();
}
});
}
Related
I have an html button with an onclick attribute which runs a jQuery AJAX function pointing to php code.
The php code writes HTML in an output HTML <select> element(the element remains hidden until the javascript runs.)
This is working great to populate the <select> when an "add another" button is clicked.
The problem is it adds one and only one. I want to be able to have a new <select> tag populate with each click of the "add another" button up to a max of 2.
The JS in question:
var genre_dropdown = function genre_dropdown() {
$('.genre_output').css('display', 'block');
$.ajax({
url:'../includes/functions/genre_dropdown.php',
complete: function (response) {
$('.genre_output').html(response.responseText);
},
error: function () {
$('.genre_output').html('Bummer: there was an error!');
}
});
return false;
}
The HTML in question:
<select name="genre_id[]" autocomplete="off" class="genre_output"></select>
<select name="genre_id[]" autocomplete="off" class="genre_output"></select>
<div class="button add-genre-button" onclick="return genre_dropdown();">+ Add Existing Genre</div>
I thought I could include 2 html <select> elements for the php to populate into, the code would execute from one to the next. I see why this is not correct, the code is running in both at the same time. I'm at a place where I'm considering have 2 buttons ("add one", "add another") but that seems redundant and not correct, especially considering I want a scale-able technique (the max may not always be 2.) I need help.
Your php request is fine.
I simply mean define a variable as your using javascript i.e.:
var sel = '<select name="genre_id[]" autocomplete="off" class="genre_output">' + response + "</select>';
and then each time you do a request it will include the response as the value of the element. This would allow you to append the parent div as many times as you want. Finally, use a simple if counter to decide whether to keep appending or not:
if ($(".genre_output").length <= 2){
$("PARENT_DIV_ID").append(sel);
};
Is this clearer? #kaari
Assuming you want to keep previous values in dropdown then you can try append() instead of html()
$('.genre_output').append(response.responseText);
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');
});
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
});
});
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.
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: