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);
}
});
Related
i have a problem with my dynamic select option. My problem is my select option didn't show anything, just show blank. I have tried many times and i am stuck
this is my html select option code
<select name="jumlahpesan" id="jumlahpesan" data-native-menu="false">
<option value="choose-one" data-placeholder="true">Choose one... </option>
</select>
and this is my ajax code to get value to fill in my select option
$.ajax({
url: host+'/skripsi3/phpmobile/cekjumlah.php',
data: { "id": getacara},
dataType: 'json',
success: function(data, status){
$.each(data, function(i,item){
$("#jumlahpesan").append('<option value="'+item.jumbros+'">"'+item.jumbros+'"</option>').trigger("create")
});
},
error: function(){
//output.text('There was an error loading the data.');
}
});
and for the last, this is my "cekjumlah.php"
<?php
session_start();
include "config.php";
$idacara=mysql_real_escape_string($_GET["id"]);
$arr = array();
$result=mysql_query("select jumlahpesan from acara where id_acara='$idacara'");
if (!empty($result))
{
while ($row=mysql_fetch_array($result))
{
$tempjum = $row['jumlahpesan'];
for($i=0;$i<$tempjum;$i++)
{
$fetchkategori[] = array
(
'jumbros' => $i,
);
}
}
}
mysql_close($con);
header('Content-Type:application/json');
echo json_encode($fetchkategori);
?>
i want to fill my select option from my looping in "cekjumlah.php" and call my php with my ajax. Thank you
this is my Ajax Response
[{"jumbros":0},{"jumbros":1},{"jumbros":2}]
I can't really help you with the PHP side of things, so if there is a problem there, I can't see it.
But you seem to be using .each() incorrectly, as each is meant to iterate over a jquery selection of elements and execute a funciton for each element, whereas your seem to be trying to use it as a foreach over data
I think you have to replace that $.each with
for item in data{
$("#jumlahpesan").append('<option value="'+item.jumbros+'">"'+item.jumbros+'"</option>').trigger("create")
}
(i'm assuming data is a JSON array, you may have to use JSON.parse(data) first judging by some of the comments on your post.
Hope someone can help me..
i made my program more simpler so that everybody will understand..
i want my program to get the value of the without submitting, i know that this can only be done by javascript or jquery so I use the onChange, but what I want is when i select an option the value should be passed immediately on the same page but using php..
<select id="id_select" name="name" onChange="name_click()">
<option value="1">one</option>
<option value="2">two</option>
</select>
<script>
function name_click(){
value_select = document.getElementById("id_select").value;
}
</script>
and then i should pass the value_select into php in post method.. i dont know how i will do it.. please help me..
You cannot do this using PHP without submitting the page. PHP code executes on the server before the page is rendered in the browser. When a user then performs any action on the page (e.g. selects an item in a dropdown list), there is no PHP any more. The only way you can get this code into PHP is by submitting the page.
What you can do however is use javascript to get the value - and then fire off an AJAX request to a php script passing the selected value and then deal with the results, e.g.
$(document).ready(function() {
$('#my_select').on('change', do_something);
});
function do_something() {
var selected = $('#my_select').val();
$.ajax({
url: '/you/php/script.php',
type: 'POST',
dataType: 'json',
data: { value: selected },
success: function(data) {
$('#some_div').html(data);
}
});
}
With this code, whenever the selected option changes in the dropdown, a POST request will be fired off to your php script, passing the selected value to it. Then the returned HTML will be set into the div with ID some_div.
not sure ..but i guess ajax is what you need..
<script>
function name_click(){
value_select = $("#id_select").val();
$.post('path/to/your/page',{"value":value_select},function(data){
alert('done')
})
}
</script>
PHP
$value=$_POST['value']; //gives you the value_select data
Post with ajax as Alex G was telling you (+1) and then handle the post with PHP. You can define a callback in Javascript which will run when the page responds.
My suggestion go with jquery. Try with this
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
<script>
$(document).ready(function(){
$("#id_select").change(function(){
var url = 'http:\\localhost\getdata.php'; //URL where you want to send data
var postData = {'value' : $(this).value};
$.ajax({
type: 'POST',
url: url,
data : postData,
dataType: 'json',
success: function(data) {
//
},
error: function(e) {
console.log(e.message);
}
});
})
})
</script>
In getdata.php
<?php
var $value = $_POST['value'];
// you can do your logic
?>
I'm using jQuery Ajax function for populating my select box.
Here is the code:
$(function(){
$("#maker").change(function(){
var selected_value = $("#maker").val();
$.ajax({
type: "POST",
url: "search.php",
data: ({_maker: selected_value}),
success: function(response){
$("#models").html(response);
}
});
});
});
The problem is this replaces the div "models" by whole search.php page!!!
I only want to populate the option values within "models".
Here is the HTML:
<div id="models">
<select id="model" name="model" style="width:170px">
<option value="Any">Any</option>
<?php
foreach($current_models as $model) {
?>
<option value="<?php echo $model; ?>"><?php echo $model; ?></option>
<?php
}
?>
</select></div>
Any help is appreciated. Thanks in advance.
So it looks like you're returning the entire HTML page, and not searching through it to find the specific part of the page. Try something like this:
$(function(){
$("#maker").change(function(){
var selected_value = $("#maker").val();
$.ajax({
type: "POST",
dataType: "html",
url: "search.php",
data: ({_maker: selected_value}),
success: function(response){
$("#models").html($(response).find('#someDiv').html());
}
error: function(){
$("#models").html('Uh oh! Something went wrong and we weren't able to process your request correctly.');
}
});
});
});
You'll notice 2 things:
I specified a dataType property. This tell jQuery what to expect. Additionally the html data type, tells jQuery to execute any JavaScript on the loaded page before rendering the page into the response object.
I'm creating a jQuery object using the response, and then using jQuery's .find() method to get the inner HTML of a specific div in the response.
Here is an example JS Fiddle, with some slight modifications for proof of concept: http://jsfiddle.net/rvk44/1/
I also just wanted to note that you may want to add an error property so that if the page ever comes back as an error, the user knows that and isn't just sitting there staring at a blank screen expecting something to happen. (I've added a basic error message in the example, see the jQuery docs for further info on what the error property is returned).
I am working on a form in which changing one "select" element modifies the values of another "select" element. The values of both the elements come from a MSSQL database. What is the best way to implement code that can accomplish this?
There are two ways that I can think to do it.
Store the table into a javascript variable and make the onchange event of the first element modify the second element.
Send a GET request to the page and reload it, using PHP to modify the second element.
I don't like the first method because storing the database from the PHP side to the javascript side seems kind of hacky and really cumbersome to do. I don't like the second way either, because reloading the page disrupts the user experience and makes him have to scroll down again.
You should use AJAX to pull in data and populate the second select element. In a nutshell, AJAX is simply a separate page request that happens behind the scenes. You can use it to load a simple HTML page or partial and display it in a DOM element, or you can use it to dynamically retrieve structured data.
The best way to do this would be using JSON (JavaScript Object Notation). In this case, you would use Javascript to make an AJAX call to a PHP page, and that PHP page would take an argument in the query string that represents the value of the first select element. With that, you would make a call to your MSSQL database to get all of the corresponding options for the second select, and then echo those out. In turn, the Javascript you use to make the AJAX request can parse the response and interpret it as a JavaScript object literal, allowing you to loop through the results and do what you want with them.
Here's an example (I'm using jQuery, since it makes AJAX really easy).
At the top of your form page:
$(document).ready(function() {
$('#select1').change(function() {
var select1val = $(this).val();
$.getJSON('/path/to/response.php', 'select1=' + select1val, function(response) {
$('#select2').empty();
if(response) {
for(var option in response) {
$('<option/>').val(option.value).html(option.label).appendTo($('#select2'));
}
}
});
});
});
And then your response.php page should look like this:
<?php
$select1 = $_GET['select1'];
// Do validation here, to make sure it's a legitimate value for select1. Never trust the
// user input directly.
// Replace this with whatever code you use to make DB queries.
$options = $mydb->query("SELECT value,label FROM select2_options WHERE select1_value=?", $select1);
echo json_encode($options);
Use Ajax if you don't want to reload the page. Read more about AJAX
$('#select1').change(function() {
var value = $(this).val();
var dataString = 'id='+ value;
if(value != '')
{
$.ajax({
type: "POST",
url: "fetchOptionsForSelect2.php",
data: dataString,
success: function(html) {
$('#select2').html(html);
}
});
}
else
{
//reset select2
$('#select2').html("<option value=''>Select value from select1 first</option>");
}
});
Here is a stand-alone example that does what you want. It might look complicated at first, but AJAX via jQuery is quite straight-forward.
This example uses two files:
1) TEST.PHP - contains the javascript/AJAX, and the HTML with the <select> controls
2) PROCESS.PHP - receives data from test.php (via AJAX), runs a MySQL lookup on that data, returns HTML back to TEST.PHP
TEST.PHP
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#workers").change(function(event) {
var w = $(this).val();
//alert('Value of w is: ' + w);
//return false;
$.ajax({
type: "POST",
url: "process.php",
data: 'worker=' + w,
success:function(data){
//alert(data);
$('#laDiv').html(data);
}
}); //END ajax
});
}); //END $(document).ready()
</script>
</head>
<body>
Worker:
<select id="workers">
<option>Roy</option>
<option>John</option>
<option>Dave</option>
</select>
<div id="laDiv"></div>
</body>
</html>
PROCESS.PHP
<?php
$w = $_POST['worker'];
$ret = '
Fruit Options:
<select id="fruitopts" name="Select2">
';
if ($w == 'Roy'){
$ret .= '
<option>Apples</option>
<option>Oranges</option>
<option>Pears</option>
';
}else if ($w == 'John') {
$ret .= '
<option>Peaches</option>
<option>Grapes</option>
<option>Melons</option>
';
}else if ($w == 'Dave') {
$ret .= '
<option>Nut</option>
<option>Jelly</option>
';
}
$ret .= '</select>';
echo $ret;
Here's what happens:
a. TEST.PHP - User selects choice from dropdown "workers"
b. change() event fires, gets value of ("w"), and sends that to process.php
c. PROCESS.PHP receives a variable key named w in its $_POST[] array, stores in $w
d. PROCESS.PHP does a MySQL lookup on the selected worker (value of $w)
e. PROCESS.PHP constructs some HTML in a var called $ret, then ECHOs it out
f. TEST.PHP receives the HTML string inside the $.ajax success function
g. TEST.PHP calls the received data data (-1 for originality)
h. TEST.PHP injects the received HTML into the DIV with id="laDiv"
Hope that helps.
Use http://www.appelsiini.net/projects/chained
<script src="jquery.chained.min.js"></script>
<select id="mark" name="mark">
<?php
foreach($select1_opt as $opt)
{
echo "<option value=$opt>$opt</option>";
}
?>
</select>
<select id="series" name="series">
<?php
foreach($select2_opt as $opt)
{
echo "<option value=$opt>$opt</option>";
}
?>
</select>
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",
});