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.
Related
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",
});
I'm trying to get a drop down box to alter a second drop down box through the use of a jquery/ajax script. Firebug is showing Jquery is working but my script isn't showing at all.
<script type="text/javascript">
function ajaxfunction(parent)
{
$.ajax({
url: '../functions/process.php?parent=' + parent;
success: function(data) {
$("#sub").html(data);
}
});
}
</script>
process.php is just a MySQL query (which works)
My initial drop down box is populated by a MySQL query
<select name="front-size" onchange="ajaxfunction(this.value)">
//Query
</select>
And then the second drop down box is just
<select name = "front-finish" id="sub">
</select>
How can I solve this?
calling inline function is not good at all... as web 2.0 standards suggest using unobtrusive JS rather than onevent attributes....check out why here..
other thigs..correct way to use ajax is by using type and data ajax option to send values in controller..
<script type="text/javascript">
$(function(){
$('select[name="front-size"').change(function()
{
$.ajax({
url: '../functions/process.php',
type:'get',
data:{'value' : $(this).val()},
dataType:"html", //<--- here this will take the response as html...
success: function(data) {
$("#sub").html(data);
}
});
});
});
</script>
and your proces.php should be..
<?php
//db query ...thn get the value u wanted..
//loop through it..
$optVal .= "<option value="someDbValue">some DDB values</option>";
// end loop
echo $optValue;exit;
updated
looks like you still have onchange="ajaxfunction(this.value)" this in your select remove that it is not needed and the ajaxfunction in javascript too...
<select name="front-size" >
//----^ here remove that
use jQuery.on() that will allow us to add events on dynamically loaded content.
$('select[name^="front-"]').on('change',function(e){
e.preventDefault();
var value = $(this).val();
ajaxfunction(value);
});
[name^="front-"] this will select all the SELECT box having name starts with front-.
In your process.php give like this
echo "<select name='front-finish' id='sub' onchange='ajaxfunction(this.value)'>";
like this you need to add the "onchange" function to the newly created select box through ajax
or you can remove onchange function and write like
$("select[name^='front-']").live('change',function(){
//Do your ajax call here
});
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 attempt to fill a drop down from a database. I query and add my result to an array. I then use json_encode to send my data to a php file.
$query="SELECT project FROM main";
$results = $db->query($query);
while ($row_id = $results->fetchArray()) {
$proj_option[] = "<option value=\"".$row_id['project']."\">".$row_id['project']."</option>\n";
$pselected=$row_id['project'];
}
$output = array( "proj" => $proj_option);
echo json_encode($output);
In my php file, I use jquery ajax to fill the drop down.
$("#turninId").change(function() {
var user_id = $("#turninId").val();
$.ajax ( {
url:"send_input.php",
type: "POST",
dataType: "json",
data:{id_selection: user_id},
success:function(response) {
for (var i=0; i<response.proj.length; i++) {
$("#exp").html(response.proj[i]);
$("#project").html(response.proj[i]); } });
});
This is great, BUT the only item in my drop down is the last item in the db. For example, my database has the following under Project:
Project: up, down, low, right
But my drop down only fills with the last entry, "right." Why is this? How can I fix it?
PHP json_encode() in while loop was similar, and I made the changes, but there is something missing here.
may be try this
success:function(response) {
$.each(response.proj,function(key,value){
$("#exp").append(value);
$("#project").append(value);
});
}
each time thru your loop in javascript you are overwriting your html. The .html() method sets the innerHTML property of the tag, so each time you call it you are resetting the html and only the last one will show. try not using a loop, instead join you response together and then call .html()
$("#exp").html(response.proj.join(''));
$("#project").html(response.proj.join(''));
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!