I am working with php and want to have a page that has a drop down on top. elements in the drop down have some id associated with them. Underneath the drop down there is a text box and underneath the text box some images. so like the following
<drop down box>
______________
<textbox _content_ loaded via ajax onchange of drop down box>
<some images loaded via ajax onchange of drop down box>
I want to query the DB everytime the drop down menu is changed and populate the text box with info from DB and load the images that were fetched from the DB.
is there some ajax library that can be used for this? I assume there will be a php page to execute the query and send the result back to the main page?
can you guys tell me some examples/tutorials I should be looking at.
Short answer: jQuery.
Here's an example of how to deal with dropdown controls in jQuery
http://remysharp.com/2007/01/20/auto-populating-select-boxes-using-jquery-ajax/
The easiest way is using Jquery. For example you could do something like this.
$('#dropdown').change(function(){ //listen for the change event of #dropdown box
$.get('example.com/script.php',
{$('#dropdown').val()}, //send the value of dropdown as GET parameter 'val'
function(data){
$('#content').html(data.content);
//first clear the image area:
$('#imgs').empty();
//Insert all the images
for(x in data.imgs){
$('#imgs').append('<img src="'+data.imgs[x]+'">');
}
}, 'json');
});
That is supposing your HTML looks something like this:
<select id='dropdown'>
<option value='1'>Option1</option>
<option value='2'>Option2 etc.</option>
</select>
<div id='content'>I contain the content, I might as well be a textarea or something else, as long is my id='content'</div>
<div id='imgs'><img src='iContainImgs.jpg'></div>
Then on the server side you create a Json object with the following structure:
content: "all the content",
imgs: array('img1.jpg', 'img2.jpg', 'etc')
You might also want to look at YUI's version on the same thing. The rich autocompletes that you can create there are pretty cool as well.
http://developer.yahoo.com/yui/autocomplete/
If you need to retrieve more complex data, You will have to retrieve json data instead of plain html.
For images you dont need ajax, just create an image tag and the image will be retrieved. You cant transmit files using ajax.
One way you could do this is to use the prototype library.
Assuming you have a page to output the HTML content for the textbox and a page that outputs the image or images, you would do something like the following:
<script type="text/javascript" src="javascript/prototype.js">
<script type="text/javascript">
function select_changed() {
// get the selected value
var parms = 'selection='+$F('selectbox');
// request the textbox value and pop it into the textbox
new Ajax.Updater(
'textbox',
'http://example.com/textbox_handler.php',
{
method: 'post',
parameters: parms
});
// request the image(s) and pop them into the image container div
new Ajax.Updater(
'image_container',
'http://example.com/images_handler.php',
{
method: 'post',
parameters: parms
});
}
</script>
<select id="select" onChange="javascript:select_changed();">
<option value="1">First Value</option>
<option value="2">Second Value</option>
</select>
<textarea name="textbox"></textarea>
<div id="image_container"></div>
Related
How do I hide a particular form field when a field is selected from a drop down in HTML?
You can't use php, as content has already been served to browser. So, a handy solution is to use javascript
<select name="foobar" onchange="checkAndHide(this.options[this.selectedIndex].value)">
<option value="right1">right1</option>
<option value="wrong">wrong</option>
<option value="right2">right2</option>
</select>
<input type="text" id="shouldHide" name="test">
<script type="text/javascript">
function checkAndHide(value){
if(value == 'wrong')
document.getElementById('shouldHide').style.display = 'none';
else
document.getElementById('shouldHide').style.display = 'block';
}
</script>
Yes you must use something that can communicate with the header which requires JavaScript or jquery, etc.
I don't have an example as I'm at work but I used jquery to load another page after a category is selected. This page generates the rest of the select fields (my sub categories) using a query and while statement ,inside the option tag once a category has been picked. There are many examples on google, just google jquery dynamic dropdown box
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
I populate a drop down box from an array that uses Javascript on the page load. But I am pulling data out of a database how would I change which one was selected? I would prefer not to have to use PHP to create the drop down boxes, as I have other non php things that use the javascript as well. What Can I do to get my Drop DownList populated from PHP?
You can see that it just calls the SelectdeptDropdown function.
<label for="collegedropdown">Collge</label>
<select name="collegedropdown" id="collegedropdown" onChange="SelectDeptDropdown();">
<option selected="selected">Choose a college</option>
</select>
<br />
<label for="deptdropdown">Department</label>
<select name="deptdropdown" id="deptdropdown">
<option selected="selected">Choose a department</option>
</select>
Javascript Code:
removeAllOptions(document.profilecreate.deptdropdown);
addOption(document.profilecreate.deptdropdown, "", "Choose One", "");
if(document.profilecreate.collegedropdown.value == 'MY CHOICE #1'){
//all options here
}
//repeat for other cases here
NOTE: removeAllOptions calls another function that simply clears the dropdown list. addOption calls a function that creates the option element.
basically you need to use an XHR Request. The XHR request will hit another end point of your php server which will return data for you to populate the dropwdown field and then you can use some smart javascript to insert into the dom.
Tne end point should ideally return a json data which will only be the dropdown values and you generate the markup on the client side this is ont compulsory but recommended.. read more abt XHR and json here.
Finally I would suggest you to use a library like jquery that gives you simple api for XHR requests and DOM manipulation using which you can get your job done quickly.
I have this webpage. It has a page called "services.php". I have several buttons (made of classes), that belong to different "package" prices i offer.
I want the links that say "Select" to autofill a form in another page, or alternativly in a popup form in the page..
I don't really know how to explain it, but as short as possible:
When link is pressed autofill form (in this or other page) with the type of package they chose. Only text autofill
What you seem to be asking is 'loading' a page pre-filled with specific information, you can do this a number of ways, either by utilizing javascript (like jQuery for instance). Or using your PHP, make links that pass variables (say a flag or a reference to pre-fill the fields -- if you want a popup or next page, etc).
Your url would like like the following for the button that a user presses (button would be a simple http link):
http://mywebsite.com/prefill.php?user=bob&package=2
This would have the values bob as the user that requests it (you can reference an id for user info here as well), and package=2 to designate your package options.
Then on the prefill.php page, you would have something that checks for:
$user = $_GET['user'];
$package = $_GET['package'];
Hope that helps
This will populate form fields with whatever you pass to the autoFill() function. This would be a same page example.
<html>
<body>
<form>
<input type="text" id="packageDescription">
<input type="text" id="packagePrice">
</form>
<script>
function autoFill(packageDescription, packagePrice) {
document.getElementById('packageDescription').value = packageDescription;
document.getElementById('packagePrice').value = packagePrice;
}
</script>
Premium Package<br>
Platinum Package
</body>
</html>
You could do something like this:
<select id="packages">
<option value="package1">Package 1</option>
<option value="package2">Package 2</option>
</select>
Submit
When the link is clicked, the following javascript will fire off:
function submitPackage()
{
var package = $("#package").val();
window.open("http://your-site.com/some-script.php?package=" + package);
}
The above will open a pop up window to a page such as this:
http://your-site.com/some-script.php?package=package1
In some-script.php you will do something like this:
You selected the package: <b><?php echo $_GET['package'];?></b>.
Or:
<?php
//Put the packages in an array:
$packages = array();
$packages['package1'] = 'Package 1';
$packages['package2'] = 'Package 2';
//...
?>
<select id="package">
<?php foreach ($packages as $name => $text):?>
<? $selected = ($name == $_GET['package']) ? 'selected' : '';?>
<option value="<? php echo $name;?>" <?php echo $selected;?>>
<?php echo $text;?>
</option>
<? endforeach;?>
</select>
The above will auto select the package they selected in a dropdown box.
if i understood your problem, you want to fill some input fields with information when the user clicks on some links
i can think of 2 ways of doing this : either have the links point to a page like services.php?req=package1 (or any other url you want) and on that page generate the input fields with the information you need (set the default values in the fields with the ones you want), or, use javascript to change the values of the forms without changing the actual page (either via ajax or predefined values)
for javascript you can use the jQuery framework, it has a pretty extensive community of enthusiasts and plenty of examples to get you started with it.
an example for your case would be
$('#btn1').bind('click', function() {
$('#input1').val("value");
$('#input2').val("value2");
});
replace btn1 with the id of the first button or link you have, input1 with the id of the first input in your form, and value with the value you want
I just did this myself. My solution was with jQuery. Just assign an id to your link. The first ID in the code is the link id and the second is the id for the input element you want to populate.
Here is the script:
<script>
$(document).ready(function() {
$('#link_id').click(function() {
$('#input_id').val( $(this).text() ).keyup();
return false;
});
});
</script>
Hope it works!
I've ran several time into the same issue, so I had to write my own script doing this. It's called Autofiller and its pretty simple but does great job.
Here is an example
http://example.com/?autofiller=1&af=1&pof=package&package=package1
So basically it takes several parameters to init the script:
autofiller=1 - init AutoFiller
af=1 - Autofill after page is loaded
pof=package - Find the parent form element of the select with name attribute package. Works also with input form elements.
package=package1 - Will set the select element's value to package1
Hope it helps you! :)
This is just me thinkign of jazzing up a mundane input field.
Ok so we have an input element, and we have pre-propagated small db table with id , name and image name
So this is what I am thinking.
We have an input element, where user begins typing. Lets say APPL...
Drop down ( for live auto suggest pops up ) with APPLE , they select APPLE and within another div element elsewhere on the page, a image div displays apple.png
Likewise if they choose banana , similarly banana.png shows in that div .
Ok so what have we got now.
Well I have auto suggest ( live search auto complete done ) all fine and dandy.
I have input element working, and they can select as they type from suggestions.
What I cannot figure out is how, to use ( possibly ajax I suppose ) hmm .. or other method, a way of displaying an image elsewhere, that reflects the choice they made.
To make things easier.
All auto completes are the exact same as the image file name, so:
APPLE becomes apple.png
CAKE becomes cake.php
I am sure js can help here. Just not sure how. I would have thought getElementById
Anyhoo .. sometimes, asking a question may invoke a response from someone who has done something similar.
Cannot show code, as the element I want to create , doesnt exist yet.
But for simplicity sake, lets take a select box method:
<select id="fruit" name="fruit">
<option value="">Please select a Fruit</option>
<option value="apple">Apple</option>
<option value="cake">Cake</option>
</select>
Presently the Auto Suggest , Auto complete looks like this:
<div class="field"><label for="fruit">Pick a Fruit </label>
Any help appreciated...
You can do this easily with jQuery. Copy the code sample below and paste it between the body tags of an html file. Replace the "myselector" element's option values with your own. When you select an item from the drop menu, the image will dynamically change.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
$(function() {
$("#myselector").change(function() { // Assign a handler.
if ($("#myselector").val() != '') {
$("#myimage").attr('src', $("#myselector").val()); // Change the image.
}
});
});
</script>
<select name="myselector" id="myselector">
<option value="">Select Image</option>
<option value="http://www.gravatar.com/avatar/e2f0c2f013205c397a7b00bc3012a027?s=32&d=identicon&r=PG">Image 1</option>
<option value="http://www.gravatar.com/avatar/06383b51463f855d7cc0f07d4566bd42?s=32&d=identicon&r=PG">Image 2</option>
</select>
<img name="myimage" id="myimage" src="http://www.gravatar.com/avatar/c259fe3371bba238ad95021e67741e9c?s=32&d=identicon&r=PG" />
Add an image on your page:
<img src="default.jpg" id="result_image" />
When your autocomplete code fills in the text, change the image as well
document.getElementById('result_image').src = autocompleted_text + ".jpg";