I have an HTML <select>:
<div id="content">
<input type="button" id="get-btn" onclick="getData();"/>
<select id="attrib-type-sel"></select>
</div>
When the user clicks the following button, I want to use jQuery's getJSON method to hit my server, pull back data, and populate the <select> with options:
$(document).ready(function() {
$.getJSON(
"some/url/on/my/server",
function(data) {
var optionsHTML = "";
var len = data.length;
for(var i = 0; i < len; i++) {
optionsHTML += '<option value="' + data[i] + '">'
+ data[i] + '</option>';
}
$('#attrib-type-sel').html(optionsHTML);
});
});
When I run this code, in Firebug, I see that the AJAX call is successful and returns the following JSON:
[
{
"id":1,
"name":"Snoopy",
"tag":"SNOOPY",
"allowsAll":false
}
]
(Only returns 1 record).
However, when back in the UI, when this code fires it creates a <select> that has 1 options whose inner HTML reads [object Object].
Can anyone spot what is going on here? It looks like my getJSON is OK, but the code to extract the JSON from the results and use it to populate my select is buggy. Thanks in advance!
it's because that data[i] is an object. Try using console.log(data[i]) to check out what it's looking like.
data[i].id and data[i].name are likely what you are looking for.
you need data[i].id & data[i].name to construct your options.
for(var i = 0; i < len; i++) {
optionsHTML += '<option value="' + data[i].id + '">'
+ data[i].name + '</option>';
}
Related
I am having an issue where my php generated select/option list is not applying to all of my dynamically generated blocks/containers. It only adds the PHP select to the last container/block instance, despite being called for each container. When troubleshooting with alerts it seems to run through all of the iterations prior to adding the containers/blocks and generating the select, hence why it always appears on the last only-
n = -1
function addDiv() {
n++;
So, a brief overview - on page initialize the code will get how many entries are in the database within a certain criteria and apply that number to 'length', which then runs the function addDiv() that many times. Usually, when adding a block one at a time via button it will populate the created block with a Select/list of Options via php in the addDiv() function, however when automating this with a loop ( the initialize() function ) the above issue occurs.
$( document ).ready(function() {
initialize();
});
function initialize() {
$.ajax({
url: 'get-entries.php',
type: 'POST',
dataType: 'text',
cache: false,
success: function(data) {
result = data;
var arrayJson = JSON.parse(data);
console.log(arrayJson);
length = arrayJson.length;
console.log(length);
for(var i = 0; i < length; i++) {
addDiv();
};
},
error: function(jqXHR) {
alert("Error while fetching data");
console.log("Error while fetching data: " + jqXHR.status + " " + jqXHR.statusText + " " + jqXHR.responseText); //improved error logging
}
});
};
here is the addDiv related code with some redactions to make it easier to read.
var n = -1;
function addDiv() {
n++;
$.post(
"json-option-generator.php",
{}
).done(
function(data)
{
$('#selectedcoin' + n).html(data);
});
$("<div class='coinmarketcap fill' id='container"
+ n +
"'><form id='"
+ n +
"' name='"
+ n +
"' class='formClass' method='post' action=''><select onchange='mySelect(this)' type='text' class='coinname' id='selectedcoin"
+ n +
"' name='selectedcoin"
+ n +
//.etc.....
"' autocomplete='off' value=''><select></select>").appendTo(".main-container");
}
and finally here is the contents of the PHP file for generating the option list based off of json data -
<?php
$json = file_get_contents("../ticker/full.json");
$decode = json_decode($json, true);
sort($decode);
echo '<select name="coinname">';
foreach($decode as $a){
echo "<option value='{$a['id']}'>{$a['name']}</option>";
}
echo '</select>';
?>
I know this is messy and may require a bit of an in depth read through, so I appreciate anyone taking the time to look.
Is there anything glaringly obvious that can help nudge me in the right direction? I have tried breaking the 'addDiv()' calls within initialize() by wrapping 'addDiv()' with a setTimeout function, but no joy.
it should work with this (I named the arguments differently for comprehension, but index and index_t can all be named n):
var n = -1;
function sendToGenerator(index){
var index_t = index;
$.post(
"json-option-generator.php",
{}
).done(
function(data)
{
$('#selectedcoin' + index_t).html(data);
}
);
}
function addDiv() {
n++;
sendToGenerator(n);
$("<div class='coinmarketcap fill' id='container"
+ n +
"'><form id='"
+ n +
"' name='"
+ n +
"' class='formClass' method='post' action=''><select onchange='mySelect(this)' type='text' class='coinname' id='selectedcoin"
+ n +
"' name='selectedcoin"
+ n +
//.etc.....
"' autocomplete='off' value=''><select></select>").appendTo(".main-container");
}
Currently I am working on a site where I receive a list of objects from a data base and I am listing them in a pop-up table. I'd like one column of the table to list the object id and another to list links which call a function for that specific object. My issue is that I do not know how to do this when appending this data to a table.
Any ideas?
var tableContent ="<tr>";
for( var i =0; i<results.length ; i++)
{
tableContent += "<td>" + results[i].get("id") + "</td>"
tableContent += "<td>" + "<a>Open ID Contents</a>" + "</td>"
//I want this link to pass results[i] to a function^
}
tableContent += "</tr>"
$("#List").append(tableContent)
You can construct your a items in this way:
var $a = $('<a class="hasPopupData">...</a>');
$a.data('popup', { /*Your data goes here */ });
$a.appendTo($parent);
And then handle clicks using code like this:
$parentTable.on('click', 'a.hasPopupData', function(){
var $a = $(this),
data = $a.data('popup');
createPopup(data);
return false;
});
Note that jQuery attaches data to DOM node in ‘native’ presentation, without converting them to JSON first.
There are a variety of ways. A simple way is to pass the variable as JSON.
var js = "afunction('" + JSON.stringify(results[i]) + "');return false;"
tableContent += "<td>" + '<a onclick="' + js + '">Open ID Contents</a>' + "</td>"
I want to append value from data base on option tag combo box. But when I first doing option tag's value empty and then I appending through AJAX then it only showing one value. But I want like all option should be visible but one should selected automatically.
my code
$('#b').on("click", "a", function () {
var patid= $(this).attr('id');
$.ajax({
type:"GET",
url:"https://localhost/patient_details1.php?patid="+patid,
dataType:'JSON',
success:function(response)
{
("#pat_type").html("");
for (var i=0;i<response.length;i++)
{
$('<option value="'+ response[i].pattype +'">'+
response[i].pattype +'</option>').appendTo("#pat_type");
}
}
}
});
});
use $('#pat_type').empty().
check when you get data from your request. You need to get it
only after loading your page.
You having typo error ("#pat_type").html("");
make it $("#pat_type").html(""); or $('#pat_type').empty();
for (var i = 0; i < response.length; i++){
listItems+= "<option value='" + response[i].pattype + "'>" + response[i].pattype + "</option>";
}
$("#pat_type").append(listItems);
// for setting selected item based on value
$('#pat_type').val('selectedvalue');
I can't call an arrays passed from the php json encode. I would concatenate 2 select state-contry-city. How can I do this??
This is the code:
I have 2 selects. I send the first value to an action:
php action into my controller:
public function regioniProvinceComuniAction(){
$response = $this->getResponse();
$request = $this->getRequest();
if ($request-> isPost()){
$post_data = $request->getPost();
$regione = (int)$post_data['regione'];
$province = (int)$post_data['province'];
}
if(isset($regione)){
$prov = $this->getProvincia($regione);
}
if(isset($province)){
$com = $this->getComuni($province);
}
$response->setContent(\Zend\Json\Json::encode(array('prov' => $prov, 'com' => $com)));
return $response;
}
This is my js file:
$("select#Regione").change(function () {
var regione = $("select#Regione option:selected").attr('value');
$.ajax({
type: 'POST',
url: '/zf-tutorial/public/regioni-province-comuni',
datatype: 'json',
data: { regione: regione },
success: function (data) {
alert (data);
}
});
});
An example of the alert function is like this:
{"prov":[{"id":"10","nome":"Genova"},{"id":"8","nome":"Imperia"},{"id":"11","nome":"La Spezia"},{"id":"9","nome":"Savona"}],"com":[]}
I tried to populate my second select via data.post like this, but the values are "undefined":
success: function (data) {
$('select#Provincia option').each(function(){$(this).remove()});
for(var i=0; i<data.length; i++){
$("select#Provincia").append('<option value="' + data[i].prov.id + '">' + data[i].prov.nome + '</option>');
}
i tried to do
for (var i = 0; i < data.prov.length; i++) {
$("select#Provincia").append('<option value="' + data.prov[i].id + '">' + data.prov[i].nome + '</option>');
}
if i set manually the var data, works fine, but with the response data doesn't work. i tried to do:
var prov = data.prov;
$("div#id").html(prov);
but it doesn't work. works only like this:
$("div#id").html(data);
and the output is the same
{"prov":[{"id":"10","nome":"Genova"},{"id":"8","nome":"Imperia"},{"id":"11","nome":"La Spezia"},{"id":"9","nome":"Savona"}],"com":[]}
You need to loop through the items in data.prov. Change your for loop to this:
for (var i=0; i<data.prov.length; i++){
$("select#Provincia").append('<option value="' + data.prov[i].id + '">' + data.prov[i].nome + '</option>');
}
jsFiddle Demo
EDIT
Solution found in comments: Can you try to change datatype in your $.ajax() call to dataType. I'm not sure if the case is important. Sounds like data is a string and not an object
Me and $.each aren't good friends, I can't seem to figure out how I should use this statement to print all my data in my JSON file. Another problem is the if statement, I tried it in many ways, but whatever I do, no data is being printed.
My JSON file
[
{
"expo":"pit",
"datum":"05.06.2011 - 05.06.2016",
"img":"images/pit_home.jpg",
"link":"exp1_index.html"
},
{
"expo":"Space Odessy 2.0",
"datum":"17.02 - 19.05.2013",
"img":"images/so_home.jpg",
"link":"exp2_index.html"
}
]
My $.getJSON script
<script type="text/javascript">
function read_json() {
$.getJSON("home.json", function(data) {
var el = document.getElementById("kome");
el.innerHTML = "<td><div class='dsc'>" + data.expo + "<br><em>" + data.datum + "</em></div></td>";
});
}
</script>
So how would I integrate the $.each statement and seperate from that, the if statement?
Try this
$.getJSON("home.json", function (data) {
var html = '',
el = document.getElementById("kome");
$.each(data, function (key, val) {
html += "<td><div class='dsc'>" + val.expo + "<br><em>" + val.datum + "</em></div></td>";
});
el.innerHTML = html;
});
Something like this?
<script type="text/javascript">
function read_json() {
$.getJSON("home.json", function(data) {
var html = '';
$.each(data, function(i, record) {
html += '' +
'<td>' +
'<a href="' + record.link + '" data-ajax="false">' +
'<img src="' + record.img + '">' +
'<div class="dsc">' +
record.expo + '<br>' +
'<em>' + record.datum + '</em>' +
'</div>' +
'</a>' +
'</td>';
});
$('#kome').html(html);
});
}
</script>
Note: I haven't tested this, so there may be a few syntax errors (mostly concerned about the quotes in the string concatenation).
I will note that you don't need jQuery's $.each for this; you can use a basic for-loop:
for (var i = 0; i < data.length; i++) {
var record = data[i];
... stuff...
}
jQuery's .each() is really useful when iterating over elements in the DOM, though. For example, if you wanted to iterate over the elements with class dsc, you could do:
$('.dsc').each(function(i, dsc) {
// Do stuff to the $(dsc) element.
});
Also, you might as well use jQuery's selectors (the $('#kome')) if you're going to use jQuery.
jQuery's API usually has solid examples for stuff; this is one such case.
$.each can iterate arrays [] or objects {}, your json contains both, so first you need to tackle array, that gives you an object on each iteration. Then you can access its properties.
jQuery each documentation
Second thing: to append to innerHTML use "+=" not "=" or you will reset html on each iteration.
var el = document.getElementById("kome");
$.getJSON('ajax/test.json', function(data) {
$.each(data, function(n, linkData) {
el.innerHTML += '' + linkData.expo + '';
});
}