I have a select input with the following code:
<select name="color" id="color" multiple class="form-control chzn-select" tabindex="8" onchange="autosave(this.id,this.value)">
It is successfully sending the function ID and select value, but seeing as one can select multiple items, it's having an issue. I can select up to 3 items without a problem, but attempting to select a 4th is causing it to pass the value of the first selected item. Not the most recently selected item. Here's the function, which sends other information such as title and date (both text inputs):
function autosave(inputid,values) {
var dataObj = {};
dataObj[inputid] = values;
$.ajax({
type: "POST",
url: "save.php",
data: dataObj,
success: function(msg) {
$('#autosavenotify').text(msg);
console.log('success');
}
})
}
HTML wise I am using Bootstrap3 if that makes a difference and here's how I'm populating the select options:
<?php
$colors = array('Red','Blue','Yellow','Purple','Green','Orange');
foreach($colors as $c) {
$selected = '';
if(in_array($c, $_SESSION['array']['colors'])) {
$selected = 'selected';
}
echo '<option value="'.$c.'" '.$selected.'>'.$c.'</option>';
}
?>
Any ideas why this might be happening? My save.php page is placing all items successfully within the array, the ajax is just sending the incorrect value for some reason.
Because you're already using jQuery, you'd probably be better off just using $(this).val( ) to get the selected options from your select. Here's a fiddle I came up with using your provided code: http://jsfiddle.net/y7NfF/1/
Another route you might consider taking would be using jQuery's .serialize() or .serializeArray() function to get all values of your form when submitting the data through ajax. However, if you want to do one element at a time, your method works just fine.
Here are a couple of links to those functions:
http://api.jquery.com/serialize/
http://api.jquery.com/serializeArray/
Related
I have a form when user select value from dropdown it can direct them to another page.but in the next page I want the selected value to be pass to another dropdown.
for instance: user select country; then go straight to the next page where there is a dropdown already selected the country value. then only they can do the next process...
note:(list item in the dropdown is same as the 1st)
hope anyone can help me.
thanks.
Simply you can store the first-page dropdown values in Session or Cookies. If you have less important things like country, cities, and address locations then you can simply use the Cookies to store the data.
You can use url parameter to pass the selected value from one page to another.
http://www.test.com/next_page.php?selected_value=12
Like above example you can pass the selected drop down value to another page in php.
You can use
$_GET['selected_value']
in next page to get selected value.
You have to get select value by doing onChange event via jquery.
After jquery, you need to pass that value to particular change event.
Lets say you have this select box
<select id="select1">
<option value"">Select</option>
<option value"1">A</option>
<option value"1">b</option>
<option value"1">C</option>
</select>
While if any value changes you need to navigate to that page taking that option value.
So this is how you can do it via jquery.
$("#select1").change(function(){
//alert();
var changedval = $(this).val();
var url = "pagename/countryname="+changedval;
window.location.href= url;
/* $.ajax({
url: url,
type: 'GET',
data: {'image_name': image_name, 'id' : id},
success: function (data) {
$("#profile_picture_display_outer").hide();
},
error: function (data) {
}
}); */
});
You can even get values via ajax as well or you can directly redirect to that particular url via appending current selected value.
Additional if you are using Codeigniter 3 then this is how you can mention routes in routes.php
$route['pagename/(:any)'] = 'Controller/methodname/$1';
I'm using Bootstrap v3 and Codeigniter... In my app, there is two select option element, for choosing state and city. I'm using ajax and when a state is selected, populated second element with related cities:
$('#state').change(function(){
var state_id = $('#state').val();
if(state_id != ""){
var post_url = "<?php echo base_url(); ?>student/get_cities/" + state_id;
$.ajax({
type: "POST",
url: post_url,
cache: true,
success: function(cities){ //calling the response json array 'cities'
$('#city').empty();
$.each(cities, function(id, city){
$('#city').append($("<option></option>").val(id).text(city));
}); //each
}
}); //ajax
}
}); //change
everything is good, just bootstrap select option element has a bad view on other browsers! (it's good just on chrome). so I decide to use bootstrap-select plugin: Bootstrap-Select
My question is: How could I populate second select option for cities? In fact, It will be populate, but so the bootstrap-select using dropdown, I must also populate it.
thanks for attention...
EDITED:
<select class="form-control selectpicker" name="state" id="state">
<!--in a foreach loop, echo all states with the proper value-->
</select>
<select class="form-control selectpicker" name="city" id="city">
</select>
SOLVED: I find the solution... simply add one line after populating select element!
$('.selectpicker').selectpicker('refresh');
As I understand your question the city select will populate from the AJAX but it loses the selectpicker functionality?
Maybe that is due to the $('#city').empty() line?
If so: then could you try starting again with a new select? E.g.
replace: $('#city').empty();
with this code
$('#city').remove();
$('#state').after( $('<select></select>').addClass('form-control selectpicker').attr({'id' : 'city', 'name' : 'city'}) );
//do your ajax stuff and add the options
$('#city').selectpicker(); //initialise it
*untested
(If the above works it may be overkill and you could simply solve the problem by re-initialising the city select after re-loading it. I.e you'd just need the $('#city').selectpicker(); line).
On my site, the user selects a person, and when the selection is made, it populates demographics about that patient below, but gives the user the options to change each demographic value. I have an html select statement for a "Prep RN" that is populated from a table of RNs when the form is loaded, but when I select a patient, I can't get it to change the select to the RN that is stored in the database and is contained in the list:
$.ajax({
url: 'php/pullselectedpatient.php',
type: 'POST',
dataType: 'json',
cache: false,
data: {Patient_UID: tempPatient_UID},
success: function(data) {
if (data.Prep_RN == 'Unassigned') {
//if unassigned, set option to unassigned
$('#selectpreprn').val('Unassigned');
} else {
//if assigned, change to selected RN
$('#selectpreprn').val(data.Prep_RN);
},
error: function() {
alert("ajax call failed.");
}
});
This code fills the option list successfully, but in case it's part of the problem, here it is:
<label for='selectpreprn'>Prep RN: </label>
<select id="selectpreprn">
<option value="empty"></option>
<?php
require('php/pullrns.php');
//loop and add the patients to the drop down list
foreach($result_rns->fetch_all(MYSQLI_ASSOC) as $row) {
echo "<option value='", $row['RN_UID'], "'>", $row['RN_UID'], "</option>";
}
?>
</select>
This results with the select filled with a 'blank', 'Unassigned', and then 3 names to choose from.
Also, this is my first time posting to this site (which is amazingly helpful), so I hope I provided everything. I have spent at least 3 hours trying different things to make this work.
To reiterate, the problem is that it doesn't select the option in the select tag when the patient is selected. It just stays blank.
This code works as intended, the issue was further down my page where I was inadvertently overwriting this selector. I copied and pasted similar code, and it got me in trouble =(
Please someone help, I am really stuck on this for 2 days :|
I have a PHP form and I would like to enable user select movies by title, or by actors.
So, I was thinking about a dropdown menu by these values (moviebyTitle, moviebyActor). For selecting movies by title, I used jQuery auto-complete which get movie titles from my DB and it works fine.
This is my code:
<select id="selectType" name="source">
<option value="">MoviesBy</option>
<option value="byTitle">byTitle</option>
<option value="byActor">byActor</option>
</select>
<input type="textbox" name= "tag" id="tags">
<div id="byActor" class="style-sub-1" style="display: none;" name="stylesub1" onchange="ChangeDropdowns(this.value)">
<select name="films[]" multiple="multiple" width="200px" size="10px">
<?php
include('moviedropdown.php');
?>
</select>
and here is the javascript:
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.1/themes/base/minified/jquery-ui.min.css" type="text/css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.1/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#tags").autocomplete({
source: "actorsauto.php",
minLength: 2
});
$("#selectType").change(function () {
if ($(this).val() == "byTitle")
$("#tags").autocomplete("option", "source", "filmsauto.php");
else
if ($(this).val() == "byActor")
$("#tags").autocomplete({
source: "actorsauto.php",
minLength: 2,
select: function (event, ui){
var selectedVal = $(this).val(); //this will be your selected value from autocomplete
// Here goes your ajax call.
$.post("actions.php", {q: selectedVal, q2: $("#selectType").val()}, function (response){
// response variable above will contain the option tags. Simply put in the dropdown.
$("#movieImdbId").html(response);
});
}
});
}
});
});
</script>
EDIT:
and this is the actions.php: (please kindly see also javascript part above)
<?php
if(isset($_GET['q']) && !empty($_GET['q']) && isset($_GET['q2']) && !empty($_GET['q2']) ){
// Here goes the cleaning code. Never use the variables received from $_GET and $_POST directly before processing it for malicious code.
$q = $_GET['q'];
$q2 = $_GET['q2'];
//$sql = fetchResults($q, $q2); // Some function which will run a database query and return some records in either object collection or arrays etc.
//I added this part to fetch data from DB
include('imdbConnection.php');
$sql = $conn->prepare('SELECT DISTINCT movieImdbId FROM movie_roleNames WHERE castName = :q');
$sql->execute(array(':q' => $q));
$html = "";
while($row = $sql->fetchAll(PDO::FETCH_OBJ)){
$option = '<option value="' . $row->movieImdbId . '">' . $row->movieImdbId . '</option>';
$html = $option;
}
echo $html; // <-- this $html will end up receiving inside that `response` variable in the `$.post` ajax call.
exit;
}
?>
My question:
I just wonder how can I add a drop down list based on the value user has typed in the textbox. For example, if user wrote "Tom Cruise" in the auto-complete textbox, a dropdown will be added that shows movies in which "Tom Cruise" has played. (I make a COMMENT in the JavaScript code where I had problem)
I really searched a lot, but all samples where to dynamically populate some dropdown (like this one, or adding a textbox based on value selected in dropdown...
Please help, I really don't mean someone write the code for me, I just want to find any sample or some way that I can learn how to do it.
Thanks,
You should have something like the following.
What you actually need is when you type into the auto complete box and select something, you need to get a hold of that value for later use. After that, you need to call the server (a php script) with an ajax call and send that value from the autocomplete box along with the value from the drop down (only if you need to). That php script will need to generate a pile of something like the following in loop and save the whole html in a variable.
<option value='v1'>Value1</option>
<option value='v2'>Value2</option>
After that, send that back to the calling ajax script and then you need to put this as the content inside that drop down that you're trying to populate.
Here's some sample code on how to accomplish the javascript part.
<select id="filmsdd" name="films[]" multiple="multiple" width="200px" size="10px">
</select>
<script>
$(document).ready(function () {
$("#tags").autocomplete({
source: "actorsauto.php",
minLength: 2,
select: function (event, ui){
var selectedVal = $(this).val(); //this will be your selected value from autocomplete
// Here goes your ajax call.
$.post("actions.php", {q: selectedVal, q2: $("#selectType").val()}, function (response){
// response variable above will contain the option tags. Simply put in the dropdown.
$("#filmsdd").html(response);
});
}
});
});
<script>
EDIT:
path/to/somefile.php would be any file which is stored in your directory along with other website files. let's call it actions.php (I have updated the $.post ajax call)
When $.post runs, it will send a request to actions.php along with two variables q and q2. These variable names can be anything.
q contains the selected value from the auto complete box.
q2 contains the selected type from the drop down.
in actions.php, you end up with something like this.
if(isset($_GET['q']) && !empty($_GET['q']) && isset($_GET['q2']) && !empty($_GET['q2']) ){
// Here goes the cleaning code. Never use the variables received from $_GET and $_POST directly before processing it for malicious code.
$q = $_GET['q'];
$q2 = $_GET['q2'];
$sql = fetchResuls($q, $q2); // Some function which will run a database query and return some records in either object collection or arrays etc.
// Initialize a variable that you will send back to your ajax call, its still waiting for this script to be completed.
$html = "";
// Assuming your function returned a list of objects. Loop through the records.
while($row = mysql_fetch_object($sql)){
$option = '<option value="' . $row->property_id . '">' . $row->property_name . '</option>';
$html .= $option;
}
echo $html; // <-- this $html will end up receiving inside that `response` variable in the `$.post` ajax call.
exit;
}
I hope this helps.
The real question is, what's the point of the second drop down box. Why dont you just display all of the movies in a "table" once they've selected the actor.
I'd suggest a unified "Search" box, and on the PHP side, querying both your movies and actors, displaying all results that way?
If they choose a autoComplete value that is of type actor, display all the actor's movies. If they select an autoComplete value that is of type "movie" - display all the movies.
Effectivly - you're eliminating the By Actor or By Movie radio in favor of a better search bar.
I am using JQuery Mobile, Javascript, HTML, JSON, AJAX, PHP and MySQL to dynamically display values from the database onto a webpage.
I have a few elements working together. First a drop down menu that populates a list view. The drop down menu elements are obtained from the database. This is done via the "on change" method, when activated it passes the selected option and the ID of the drop down menu to a JSON function, which takes care of retrieving the data from the database with the help of PHP and functions. I also have a radio button that works as a filter to the type of results that are to be retrieved from the database and displayed on the list view.
My problem is hopefully simpler than it looks. I am trying to pass my JSON function the value of the selected option from the drop down menu. I know that the JSON wants an object, but I am having problems doing this.
To illustrate how I try to do this, let's say I have a drop down list with fruits, I have a radio button that allows you to choose from Red fruits or Green fruits, and a list view to display my results:
<div data-role="fieldcontain">
<fieldset data-role="controlgroup" data-type="horizontal" data-mini="true">
<input type="radio" name="radio" id="red" value="1" checked="checked" onchange="change_fruit_color('red');"/>
<label for="red">Red Fruits</label>
<input type="radio" name="radio" id="green" value="2" onchange="change_fruit_color('green');"/>
<label for="green">Green Fruits</label>
</fieldset>
</div>
<li>
<label for="fruit" class="select">Fruits</label>
<select name="fruit" id="fruit" data-mini="true" onclick="populate_list('fruit', this);" onchange="clear_dropdown('fruit'); refresh_dropdown('fruit');">
<option value=""></option>
</select>
</li>
Note that I have a few extra functions, refresh_dropdown() and clear_dropdown() handle refreshing my drop down list items, nothing to worry about there. The populate_list function works good too. The issue is regarding the logic of the change_fruit_color() function:
function change_fruit_color(fruit_color)
{
var selected_value = $("#fruits option:selected").text();
if(selected_value)
{
switch(fruit_color)
{
case "red":
populate_list('red', selected_value);
break;
case "practice":
populate_list('green', selected_value);
break;
}
clear_dropdown("fruit");
refresh_dropdown("fruit");
}
}
function populate_list(selected_fruit, this_menu)
{
var find_fruit_url = server_root_url + 'fruit/find_fruit.php';
var value = this_menu.options[this_menu.selectedIndex].value;
var params = {
control: selected_fruit,
value: value
};
$.ajax({
type: "POST",
url: find_fruit_url,
async:false,
data: params,
success: function(json){
json_populate(json, selected_fruit, value);
}
});
}
As you can see, I can call the populate_list three times; once within the "onclick" function of the drop down list, the other within the change_fruit_color that's called via the "onchange" event in the radio button box. In here is where the issue lies.
I tried to make a sample of my general issue so that I write way less code for all of you to read through. Any help on how to proceed would be greatly appreciated!
You're passing selected_value as the second argument to populate_list, but your second argument (this_menu) is supposed to be the select if you want to get the options property on it. I would rename the this_menu argument to selected_value and use that instead of fetching the value from the select again.
Please post your json_populate function to be check what's going on there.
Maybe a time saver would be how you properly format a JSON array. Remember that you've have to use the following notation when dealind with JSON arrays...
var myJsonArray = {
"name_1": value1,
"name_2": value2
};
So maybe your param's var should go as this:
var params = {
"control": selected_fruit,
"value": value
};
Hope this helps.
Luis M.
I solved a similar issue by using this code:
$.post(urlpath,formData,'json')
.done(function(data) {
$.each(data.collection, function (key, value) {
$("#priorityid").append("<option value='"+value.codemaster_detls_name+"'>" + value.codemaster_detls_name + "</option>");
})
Priorityid is the id of the particular list, codemaster_detls_name is my mysql table name from which I am retrieving data.