I have a static combobox in a php web page.I want when selecting an item from this combobox (example 'item 1') the php execute a SELECT statement to get the value of a field named 'item 1' from a table X in my database.
How that can be done ?
You will need to use AJAX to do this. Here is a simple example:
HTML
Just a simple select box, for the purposes of this example.
<select id='items'>
<option value='1'>Item 1</option>
<option value='2'>Item 2</option>
<option value='3'>Item 3</option>
</select>
JavaScript
I'm going to use jQuery here, you don't have to if you don't want to but it makes AJAX a whole lot easier.
The browser will listen for a change event on the select box and perform an AJAX request to the appropriate URL. When the server sends back data, the success function will be triggered. Read more about .ajax() in the jQuery documentation.
$(document).ready(function() {
$('#items').change(function() {
$.ajax({
type: 'GET',
url: 'pageWithPhpCode.php',
data: {
itemID: $(this).val()
},
dataType: 'json',
success: function(data) {
// do whatever here
console.log(data);
}
});
});
});
PHP
Here I'm retrieving the data, JSON encoding it, and sending it back to the client with the appropriate MIME type. I'm not sure how you connect to your MySQL database, but I'm using PDO here.
Keep in mind that mysql_* functions are deprecated.
<?php
if(isset($_GET['itemID'])) {
$db = new PDO();
// ... connect to your database, however you do it
$q = 'SELECT * FROM items WHERE id = :itemid;';
$stmt = $db->prepare($q);
$stmt->bindValue(':itemid', $_GET['itemID'], PDO::PARAM_INT);
$stmt->execute();
$output = $stmt->fetchAll(PDO::FETCH_ASSOC);
header('Content-Type: application/json; charset=utf-8');
echo json_encode($output);
}
Related
is it possible to add a new option dynamically to a select box and also can be added to the database using Ajax. i am looking for a button which appends new option to the select box as well as to add that field to the database. Thanks...
EDIT 2
is it possible to update the select box values without page refresh, The case is when i adds new data to database and not making use of .append here...
Try this
This is for add new option in select
$('select').append('<option value="0">--Select--</option>');
And after adding new option you can call ajax
$.ajax({
url:'url',
data:'data',
type:'post',
success:function(data){
}
});
In server side put code to save data in database.
Edit
$.ajax({
url:'url',
data:'data',
type:'post',
success:function(data){
//data will be list of values which you want in options and this sent from server side in json result
$(data).each(function(index,item){
$('select').append('<option value="'+item.val+'">'+item.name+'</option>');
});
}
});
Do you mean something like this?
JSFiddle: http://jsfiddle.net/s4yh3Lor/1/
HTML
<button id="pop-btn">Populate</button>
<select id="options-box">
<option value='1'>Option 1</option>
</select>
jQuery
$(document).ready(function(){
$("#pop-btn").on("click",function(){
value = "2";
name = "Option 2";
$("#options-box").append("<option value='"+value+"'>"+name+"</option>");
$.ajax({
url: "addtodb.php?value="+value+"&name="+name,
type: "GET",
success: function(data) {
alert(data);
}
});
});
});
PHP - While this is valid, make you sure sanitize your inputs into the query to avoid SQL Injection.
$value = $_GET["value"];
$name = $_GET["name"];
mysql_query("INSERT INTO tablename (name,value) VALUES ('$name','$value')");
I have created a script which fills the second combobox with the value of the first one. But it is not quite what I want to do. I want to fill the second combobox with the result of a SQL query based on the item which was selected in the first combobox.
Here is my javascript:
<script type="text/javascript">
function selectDropdown(){
var dropdownValue=document.getElementById("dropdown").value;
$('option[value=st]').text(dropdownValue);
}
</script>
first combobox:
<select id="dropdown" name="dropdown" onchange="selectDropdown()">
<option value="dd">--take an option--</option>
<?
$standard = Env::value('standard');
if (!$status)
$statement = "select code from standard";
foreach ($db->query($statement )->fetchall() as $row)
echo "<option".($row == $standard ? ' selected ' : '').">$row[0]</option>";
?>
</select>
and the second one in which I want to show the result of the query: $q= select request.code from request inner join standard on ( request.standard_id=standard.id) where standard.code=$st.
<select name='st' class='txt'>
<option value="st"><? echo $st; ?></option>
</select>
Can anyone give me a hint where I should put query execution? Or just point me what I am doing wrong?
Use jQuery's ajax call to make a request to the server each time when first dropdown selection has been changed. On the server side create a script which will receive that request and return corresponding records for 2nd dropdown in JSON format, which then can be easily processed by javascript. For using ajax see this link: http://api.jquery.com/jQuery.ajax/
It will be like:
jQuery.ajax({
method: "POST",
url: "http://domain.com/path/to/script.php",
data: value_of_selected_item_from_first_dropdown,
success: function(response) {
// Set 2nd dropdown values to those received via response
}
dataType: "json",
});
EDITED:
SQL
$valuefromjs = $_REQUEST['var'];
$result6 = "SELECT DISTINCT $valuefromjs FROM persons ORDER BY $valuefromjs ASC";
$result7 = mysql_query($result6);
$num = mysql_num_rows($result7);
$dataRanges[0] = array('dataRanges');
for ($i=1; $i<($num+1); $i++)
{
$dataRanges[$i] = array( (int) mysql_result($result7, $i-1) );
}
echo json_encode($dataRanges);
HTML
<select id="combo2" class="combo" data-index="2"></select>
jQuery
$('#1combo').on('change', function () {
var jsonVar = $.ajax({
url : "visits/comboquery.php?var="+$(this).val(),
dataType: "json",
async: false,
success: function(response) {
}
}).responseText;
for (var i=1; i<objVar.length;i++)
{
$('#combo2').html("<option value="+objVar[i]+">"+objVar[i]+"</option>");
}
});
QUESTION:
I have an array with query results. Now i need that results be the combo2 options, what is wrong?
To my understanding the choice from combo1 will define which query to run for building combo2.
The issue: your PHP for building the combo2 is parsed at the server side i.e. the PHP code is always finished executing by the time the page reaches the user's browser and your javascript begins to execute.
If you have a finite set of possible queries that can generate the seconds combo (which should be the case since combo1 has a finite number of options), you can create all of them, each with a different id, and maintain them hidden (css "display: none").
<select id="firstCombo2" class="combo2">
...
</select>
<select id="secondCombo2" class="combo2">
...
</select>
etc.
Now, when the user makes a selection from combo1, you can decide which one of the hidden combo2's you are going to display (css "display: block").
$('select#combo1).on("change", function(){
$('select.combo2').css('display','none'); //hide all combo2's
if($(this).val()=='Opt1'){
$('select#firstCombo2').css('display','block');
}else if($(this).val()=='Opt2'){
$('select#secondCombo2').css('display','block');
}
}
You should use AJAX in order to solve your problem.
on combo1 onChange call an AJAX call to your server and send selected value of combo1.
Then in your php code run query with value received from AJAX request and construct a new combo box with options in string and echo back that string. You can use that AJAX response to populate new combo2.
hey I am trying to populate one select dropdown on the basis of another one using ajax. I have one select populated with portfolios and the 2nd one is empty. when I select an option from the 1st select box. I call an ajax function in which I send the selected portfolio id, In the ajax method I find the groups for the selected id, how can I populate the 2nd select with the groups I found. My code is
The form which contains two selects
<form name="portfolios" action="{{ path('v2_pm_portfolio_switch') }}" method="post" >
<select id="portfolios" name="portfolio" style="width: 200px; height:25px;">
<option selected="selected" value="default">Select Portfolio</option>
{% for portfolio in portfolios %}
<option get-groups="{{ path('v2_pm_patents_getgroups') }}" value={{ portfolio.id }}>{{ portfolio.portfolioName }}</option>
{% endfor %}
</select><br/><br/>
<select id="portfolio-groups" name="portfolio-groups" style="width: 200px; height:25px;">
<option selected="selected" value="default">Select Portfolio Group</option>
</select><br/>
</form>
The JS
<script>
$(document).ready(function(){
$('#portfolios').change(function() {
var id = $("#portfolios").val();
var url = $('option:selected', this).attr("get-groups");
var data = {PID:id};
$.ajax({
type: "POST",
data: data,
url:url,
cache: false,
success: function(data) {
//want to populate the 2nd select box here
}
});
});
});
</script>
Controller method where I find the groups for the selected portfolio
public function getgroupsAction(Request $request){
if ($request->isXmlHttpRequest()) {
$id = $request->get("PID");
$em = $this->getDoctrine()->getEntityManager();
$portfolio_groups = $em->getRepository('MunichInnovationGroupPatentBundle:PmPatentgroups')
->getpatentgroups($id);
return $portfolio_groups;
}
}
Any idea how can i send the portfolio groups and populate the 2nd select
thanks in advance
Use getJson instead of ajax();
Json (JavaScript Object Notation) , is the most easiest way to send structured data between php and javascript.
I Assuming here that the controller respond directly to the ajax query and that $portfolio_groups is an associative array with "id" and "name" as keys or an object with this same properties.
In your PHP controller send json data:
public function getgroupsAction(Request $request){
if ($request->isXmlHttpRequest()) {
$id = $request->get("PID");
$em = $this->getDoctrine()->getEntityManager();
$portfolio_groups = $em->getRepository('MunichInnovationGroupPatentBundle:PmPatentgroups')
->getpatentgroups($id);
echo json_encode($portfolio_groups);
}
}
Then use getJson to retrieve data and iterate over it :
$.getJSON(url, data, function(result) {
var options = $("#portfolio-groups");
$.each(result, function(item) {
options.append($("<option />").val(item.id).text(item.name));
});
});
Have a look to the getjson documentation for more detail about it
Check out this XML tutorial (someone out there is going to flame me for linking to w3schools) it's a good start.
AJAX requests are, in VERY broad terms, calls which make a browser open a window that only it can see (not the user). A request is made to the server, the server returns a page, the script that made the request can view that page. This means that anything which can be expressed in text can be transmitted via AJAX, including XML (for which the X in AJAX stands for).
How is this helpful? Consider, if you are trying to populate a drop down list, you need to return a list of items to populate it with. You COULD make an ajax call to a page http://www.mysite.com/mypage.php?d=select1 (if you are unfamiliar with GET and POST requests, or are a little in the dark regarding the more utilitarian aspects of AJAX, another full tutorial is available here) and have it return a list of items as follows:
item1
item2
item3
...
And scan the text for line breaks. While this certainly would work for most cases, it's not ideal, and certainly won't be useful in all other cases where AJAX may be used. Instead consider formatting the return in your PHP (.NET, ASP, whatever) in XML:
<drop>
<item>item1</item>
<item>item2</item>
<item>item3</item>
</drop>
And use Javascripts built in parser (outlined here) to grab the data.
What I would do is to use the $.load() function.
To do this, your getgroupsAction should return the options html.
The JS:
<script>
$(document).ready(function(){
$('#portfolios').change(function() {
var id = $("#portfolios").val();
var url = $('option:selected', this).attr("get-groups");
var data = {PID:id};
// Perhaps you want your select to show "Loading" while loading the data?
$('#portfolio-groups').html('<option selected="selected" value="default">Loading...</option>');
$('#portfolio-groups').load(url, data);
});
});
</script>
I don't know how $portfolio_groups stores the data, but let's say you'd do something like this in your response:
<?php foreach($portfolio_groups as $p) : ?>
<option value="<?php echo $p->value ?>"><?php echo $p->name ?></option>
<?php endforeach ?>
This way, the select will be filled with the options outputted by getgroupsAction.
The easiest way would be to return json string from your controller and then process it in the 'success' call of the $.ajax.
Lets assume, that your $portfolio_groups variable is an array:
$portfolio_groups = array('1'=>'Portfolio 1', '2' => 'Portfolio 2');
then you can return it from controller as json string like this:
echo json_encode($portfolio_groups);
Then in your jQuery ajax call you can catch this string in the response (the 'success' setting of the $.ajax). Don't forget to add setting dataType: 'json'
Roughly, your $.ajax call will look like this:
$.ajax({
type: "POST",
data: data,
url:url,
cache: false,
dataType: 'json', // don't forget to add this setting
success: function(data) {
$.each(data, function(id, title){
var node = $('<option>').attr('value', id).html(title);
// this will simply add options to the existing list of options
// you might need to clear this list before adding new options
$('#portfolio-groups').append(node);
});
}
});
Of course, you will also need to add the checks if the data is not empty, etc.
Supposing that the function getgroupsAction stays in a flat php controller ( not inside a class ) you should tell the server to execute the function
so at the end of file being called by ajax you should barely call the function first ( probably you did it! )
For your patents group result set, you can generate the select by php or by javascript
In first case you should do this:
//php
$options = getgroupsAction($_REQUEST);
$return = "<select name =\"name\" id=\"id\"><option value=\"\"></option>";
foreach( $options as $option){
$return.= "<option value=\"$option\">$option</option>";
}
$return .= "</select>";
echo $return;
Then in Javascript:
// javascript
var data = {PID:id};
$.ajax({
type: "POST",
data: data,
url:url,
cache: false,
success: function(data) {
//inside data you have the select html code so just:
$('#divWhereToappend').append(data);
},
error: function(data) {
//ALWAYS print the error string when it returns error for a more easily debug
alert(data.responseText);
}
});
I have three drop down menus that query a MYSQL database depending on what a user selects. One of the menus is dynamic and but I can't get it to return data - the other two work fine. I think i need to catch the JS onchange event and then pass it to PHP in order to run the query but I am going in circles at present.
Below is what i am trying to do. All the values are stored in the <head> section - I have added my query and select html and on change event below.
$category=$_POST['Category'];
$subcategory=$_POST['Subcategory'];
$destination=$_POST['Destination'];
$result = mysql_query("SELECT * FROM travel WHERE Category='$category'
AND Subcategory='$subcategory' AND Destination='$destination'")
or die(mysql_error());
$row = mysql_fetch_assoc( $result ) ;
<select name="subcategory" id="subcategory onchange="javascript:
dropdownlist(this.options[this.selectedIndex].value)">
<option value="">Select Sub-Category</option>
Try this jQuery:
$(document).ready(function() {
$('#myelement').change(function() {
$.ajax(
serverUrl,
{
data: { /* Put your input data in here as a hash */ }
type: 'POST',
dataType: 'json',
success: function(data, textStatus, jqXHR) {
/* Put your response handler in here */
}
}
);
});
});
I'll leave you to do the server bit - you'll need json_encode(). Have fun!