AJAX Controlled Multiple Select Box Strategy - php

I've done some reading on AJAX, and would like to create a listbox, that controls what is displayed in a separate textbox located within the same form. The backend of the website is handled in php, and the possible values and whatnot is stored within the MySQL database via php. What's the best way of obtaining the listbox values as well as the textbox values, and if your answer is JS, how do I create multiple selects in JS?

Well this is really a wide theme question.
My approach would be to create a listbox with php and put an onchange event that will call an ajax with value parameter, that ajax call will fill textbox.
You should use jquery, read some documentation here http://docs.jquery.com/Main_Page

multiple select listbox
<select id="choices" multiple="multiple" .. >
If you were using jQuery you could do something like:
$("#choices").change(function() {
var choices = {};
$("#choices option:selected").each(function() {
choices[this.id] = $(this).val();
});
$.post("http://example.com/choice_handler.php", choices, function(content) {
$("#textarea").val(content);
});
});
choice___handler.php would look at $_POST to retrieve the id/value pairs and produce content that would be returned and then assgned as the value of a textarea.
Note: i haven't tested/debugged any of this - just some code sketching here

Related

jQuery what is the best way to submit meta data of dynamically created elements?

Basically I am creating a number of rectangles using jQuery and adding these to the DOM e.g.
var divElement = jQuery('<div/>').attr({
'class': 'ui-widget-content resizable'
});
I am then allowing the user to fill out input fields for the selected rectangle e.g. name, width, height. This data is currently being added to each element via .data method.
Once the user has created all their elements along with their associated meta data, I would like them to submit the page so I can do some server side scripting in PHP.
Just wondering what the best way is to submit this data - as I understand it, I could dynamically create form elements or use the jQuery.post method.
Please can anyone advise on the best method (perhaps a different one altogether) and any tips on how to set this up e.g. using [] brackets in the name of each element to create arrays etc..
A good way will be to construct an object, or array, and fill it with all the data you wish to save. and then send it to your server using $.post() for storage.
var data = new Array;
data['height'] = 100;
data['width'] = 200;
$.post('save.php', data, function(result){
// test if successful and carry on
});
source: http://api.jquery.com/jQuery.post/

load list of values to the listbox based on another listbox value

load different list of values(from a database) to listbox when changing another listbox value
for ex:
First list box : -select grade-
Second List box : -select Subject-
Please Help
Thank You
The basic idea is to submit that data to the server (either by POST back, or AJAX), and then respond with the data.
<select id="mySel" onChange="sendData()">
What I've done there is added a javascript function to be called every time the drop down value has changed.
function sendData() {
$.post("processData.php", {selected: $(this).val()}, updateData(data));
}
This is a skeleton of the function I'd write for the select onChange event. I've skipped a step or two here and used jQuery to help create an AJAX request back to the server. I will be calling my php script processData.php to help process which element was selected. The {} contain the data I want to send to the server, in this case the selected value. And Finally what to do once I get data back from the server.
Now I'd be in my php file and able to process the data I took in and run my query to get the new data. Once done I simply json_encode the data and respond with it.
Now back in the javascript world my UpdateData function is automatically called and passed the json data.
function updateData(data) {
var select = '<select name="sel2">';
$().each(data, function(index, val){
select += '<option name="'+ index+ '">'+ value+ '</option>';
});
$("#mySel").parent.append(select);
}
That would allow me to generate a new select list from the returned data (assuming a key/value paired array in json).
I haven't actually tested any code and it's designed to be more of a guide and pseudo-code.
When a user selects a value from one select element, send an XMLHttpRequest to get the data to populate the second select element.

javascript and PHP variable passing

I have two select box and the second select box value is dependent on the first select box. So basically what I am trying to do is that after a user makes a selection on the first select box, it will then store this value of the first select box as a variable. Then it will query my database to populate the second select box, based on the first selected value. Question is, how do I pass in the var I have in the first select box to PHP? I've read other post and people said it's impossible, but if it is then how do people do this? AJAX?
If I understand correctly, then yes, using AJAX is really your only choice.
Indeed, you can, with AJAX, call something like 'getSelectionData.php?data=' + select1.value, which returns a JSON array of data based on the selection in the first select box. You then parse the data and enter it into the second select box.
Add a onchange event listener to the first select box:
document.getElementById("select1").addEventListener("change", function(ev){
var yourstoredvariable = this.value;
someFunctionThatCallsAjax(yourstoredvariable);
}, true);
I assume that you have a Country/City dropdowns, You can do it in two ways, the good AJAX way and the bad way (refresh page on change), I'm gonna describe the good way in jQuery, or at least what I see it good.
this is the client-side (i.e. client) code:
<select id="country">
<option value="1">Canada</option>
<option value="2">UK</option>
</select>
<select id="city" disabled="disabled"></select>
<script type="text/javascript">
$('#country').change(function(){
$('#city').load('/ajax-city.php', {id: $(this).val()});
});
</script>
This is the ajax-city.php code (server):
<?php
$countryId = $_REQUEST['id'];
$cities = array(); // Get it from db, using mysql_query or anything you want to use
foreach($cities as $city) {
echo "<option id=\"{$city['id']}\">{$city['name']}</option>";
}
PS. you would need to include jQuery in your html code, and of course put the two files in the same directory (or change the $.load path).
This particular code is not tested, I've just written it. But it usually works fine to me this way.
You will have an onchange event on the first <select> that will query the server using Ajax with the value of the selected <option> that will return the <option> elements with which to populate the 2nd <select> element.
Question is, how do I pass in the var I have in the first select box to PHP?
I see no problem here.
Just usual, an ordinary html form using GET method.
What's so big about it?
If I see correct you're using Jquery. So you can do this like this:
$('#idOfSelectBox1').change(function(){
jQuery.ajax({
type: "GET",
url:"yourdomain.com/script.php",
data:"selectBox:'"+$('#idOfSelectBox1').val()+"'",
success:function(result){
//do smth with the returned data
}
});
});
in the script.php do your magic and echo what you want to pass back to js

jQuery: Using autocomplete to add values to two fields instead of one

I want to use the autocomplete plugin for jQuery to populate not one, but two fields when selecting one of the autocomplete values - the name of a band is entered in the #band input field, but the band url (if exists) should also automatically be added to the #url input field when selecting the band name.
Right now I simply have an un-pretty list in an external php file from which the autocompleter takes it's values:
$bands_sql = "SELECT bands.name, bands.url
FROM bands
ORDER BY name";
$bands_result = mysql_query($bands_sql) or print (mysql_error());
while ($bands_row = mysql_fetch_array($bands_result)) {
$band_name = $bands_row['name'];
$band_url = $bands_row['url'];
echo $band_name."\n"; #needs to be replaced with an array that holds name and url
}
My autocomplete function looks very basic atm, but as I'm an absolute beginner when it comes to jQuery (and also clueless when it comes to PHP arrays), I have no idea how to tell it to populate two fields and not one.
$(document).ready(function() {
$("#band").autocomplete('/autocomplete-bands.php');
});
Is that even possible?!
sure check use result hadler so you can then do what you want once a choice has been made
I don't know about the particular plug-in you are using, but I would use the autocomplete widget for jQuery UI instead of a third party plug-in.
Here is an example of what you are looking for:
$("#band").autocomplete('/autocomplete-bands.php').result(function(event, data, formatted) {
if (data)
$('#url').(data['url']);
else {
// no data returned from autocomplete URL
}
});
I don't know much about php, but whatever the format of your data that is returned should be put where the data['url'] is currently in order to populate the #url input.

need to get value from the database and populate a drop down list using jQuery

I need to populate a dropdown list when I select a certain value
and the options need to be queried from the database.
Can I achieve this from jQuery ?
If I can then please I would appreciate any help..
You can do it with jQuery and AJAX
jQuery.post('dropdownValues.php', {parameterSentToServer1:'value', param2:'value2'}, function(data){jQuery('#mydropdown option').remove(); //Remove current options
for (var option in data.results){
jQuery('#mydropdown').append('<option value="'+option.value+'">'+option.name+'</option>');
}}, 'json');
in dropdownValues.php you'll need to build a json object with the result of the sql query, the object must be in this format(for working well with the above script):
echo '{results:[{value:1, name:'Option1'}, {value:2, name:'Option2'}]};
Does "drop down list" refer to a popup menu (e.g. a <select> element)? If so, you can populate it as follows:
var data = ["Hello World!", 42, true, "Foo"];
var select = document.getElementById("myPopupMenu");
for (var i = 0, l = data.length; i < l; i++)
{
var option = new Option();
option.innerHTML = data[i];
select.appendChild(option);
}
However, this is in plain JavaScript—I'm not sure what the jQuery syntax would be.
Steve
Note that appending each <option> to the <select> will reload the DOM for each append. This can become very slow if you have a lot of options.
It is more efficient to build the whole <select> with its option in a string and then replace the existing one.
You can definitely achieve this. You need to use AJAX.
Ajax is a subject all in itself, but basically what you will do is call a javascript function when a selection is made from the dropdown. The javascript function will request a page from your server via Ajax, and the server will return a small chunk of data, which you can then use (from Javascript again) to re-populate the second drop down (or whatever).
Google around for how to do Ajax with Jquery. Here's a page that might get you started: http://www.ajaxlines.com/ajax/stuff/article/use_jquery_ajax_to_create_options_in_a_dropdown_menu.php

Categories