How to properly append json result to a select option,
sample json data
Ajax code:
$.ajax({
url: 'sessions.php',
type: 'post',
datatype: 'json',
data: { from: $('#datepicker_from').val().trim(), to: $('#datepicker_to').val().trim() },
sucess: function(data){
var toAppend = '';
//if(typeof data === 'object'){
for(var i=0;i<data.length;i++){
toAppend += '<option>'+data[i]['id']+'</option>';
}
//}
$('#sessions').append(toAppend);
}
});
html code:
<p>Sessions:
<select id="sessions"></select>
I already set to my php file
header("Content-Type: application/json");
Use $.each to iterate through your JSON array that you receive from ajax call.
Note:- the spelling of success, you have written sucess.
success: function(data){
var toAppend = '';
$.each(data,function(i,o){
toAppend += '<option>'+o.id+'</option>';
});
$('#sessions').append(toAppend);
}
You can do append to the DOM directly inside the each loop but it is always better to concatenate with string and then adding to the DOM later. This is a cheaper operation since you are accessing DOM only once in this case. This might not work in some complex scenarios though.
success: function(data) {
var options = "";
for (var i = 0; i < data.length; i++) {
options += "<option>" + data[i].id + "</option>";
}
$("#sessions").html(options);
}
If your response is in multidimensional array then try as follows
success: function(data) {
var options = '';
for (var i = 0; i < data.length; i++) {
for (var j = 0; j< data[i].length; j++){
options += '<option value="' + data[i][j].product_id + '">' + data[i][j].name + '</option>';
}
}
$("#products").html(options);
}
I hope this will help you to append
for(i=0; i<data.length; i++) {
$('#sessions').append("<option value="+data[i].id+"/option>");
}
Let You receive json data in parameter data
var obj = JSON.parse(data);
for(i=0; i<data.length; i++) {
$('#sessions').append("<option value="+obj[i].id+">"+obj[i].name+"</option>");
}
Please try the below code this may help you.
these code i used in spring boot MVC
JSON Data
[{"name":"Afghanistan","code":"af"},
{"name":"Albania","code":"al"},
{"name":"Algeria","code":"dz"}]
JQuery Code
var jsonData = '${restData}';
var obj = JSON.parse(jsonData);
for (i in obj) {
$('#selectList').append(new Option(obj[i].name, obj[i].code));
}
Related
Below is my code to load the combo using a txt file:
$("#Combo1").change(function() {
$('#Combo2').empty();
$.ajax({
url: 'File.txt',
type: 'get',
success: function(txt){
var value = [];
var txtArray = txt.split('\n');
for (var i = 0; i < txtArray.length; i++)
{
var tmpData = txtArray[i].split(',');
if (!value[tmpData[1]])
{
value.push([tmpData[1]]);
value[tmpData[1]] = true;
}
}
$('#Combo2').empty();
$.each(value, function(i, p) {
$('#Combo2').append($('<option></option>').val(p).html(p));
});
}
})
});
$("#Combo1").trigger("change");
Here on change of Combo1, this will be called. The Ajax is used to read the content of File.txt File.txt has a "," seperated two columns, out of which I am willing to print coulmn2. Given below are the contents of File.TXT.
A,31JAN
B,25JAN
C,31JAN
D,6JAN
E,6JAN
I was to load the above dates in Combo2. With the above code, I am able to ignore 31JAN. But 6JAN is getting repeated. In short, the value which is given at the last row gets repeated. Rest is fine.
Try this:
var txt="A,31JAN\nB,25JAN\nC,31JAN\nD,6JAN\nE,6JAN";
var txtArray = txt.split('\n');
for (var i = 0; i < txtArray.length; i++)
txtArray[i] = txtArray[i].split(",").pop();
var value = txtArray.reduce(function(a,b){if(a.indexOf(b)<0)a.push(b);return a;},[]);
console.log(value); //returns array
Also, give this a read: https://stackoverflow.com/a/9229821/9920079 :)
Is it possible to use response.DATA[i][j] in a CFIF statement.
chkUsernameUnique = function(theUsername){
$.ajax({
type: "GET",
url: "/book.cfc",
data: {method: "testFunction", datum: $('#date').val(), returnFormat: "JSON"},
dataType: "json",
success: function(response) {
var str = '<table><tr>';
var i;
var j;
//loop over each column name for headers
for (i = 0; i < response.COLUMNS.length; i++) {
str += '<th>' + response.COLUMNS[i] + '</th>';
}
str += '</tr>';
//loop over each row
for (i = 0; i < response.DATA.length; i++) {
str += '<tr>';
//loop over each column
for (j = 0; j < response.DATA[i].length; j++) {
str += '<td>' + response.DATA[i][j] + '</td>';
}
str += '</tr>';
}
str += '</table>';
$('#debugDiv').html(str);
},
error: function(ErrorMsg) {
console.log('Error');
}
});
}
What I want to do is something like:
<cfif response.DATA[i][j] is 3> str += '<td>test</td>';</cfif>
This returns the following error message: variable [RESPONSE] doesn't exists.
The response variable is the server response for your AJAX request and you are working with it on clientside. Thus you are still in the realm of JavaScript:
if (response.DATA[i][j] == 3) { str += '<td>test</td>'; }
ColdFusion (i.e. <cfif>) is executed on serverside, thus cannot be used to evaluate data during runtime (after the browser requested an URI).
I am using below anchor tag,in using json object.How to write it using html helper method.
success: function (data) {
var str = "";
for (i = 0; i < data.length; i++) {
str += "<a href=/Home/GetArtistRelatedData?str=" + data[i].ArtistName + " target='_blank' style='color:gold;'>" + data[i].ArtistName + "</a><br/>";
}
$("#mm").append(str);
}
Let's say I have this link called: http://user.com/1345, and that link returns a JSON. Now I want a tool that can loop from http://user.com/1 to http://user.com/1345 and save that JSON data to a file. Anyone knows a good tool for that?
In JavaScript:
var allData = [], xhr;
for (var i = 1; i <= 1345; i++) {
xhr = new XMLHttpRequest();
xhr.addEventListener("load", function () {
allData.push(JSON.parse(this.responseText));
});
xhr.open("GET", "http://user.com/" + i);
xhr.send();
}
window.open('data:text/json;charset=utf8,' + encodeURIComponent(allData), '_blank');
You can use C# to do so.
for (var i = 0; i < 1345; i++)
System.IO.File.WriteAllText (i.ToString (), new WebClient.DownloadString ("http://user.com/" + (i + 1).ToString()));
My request ajax with json_encode:
[{"idHome":"1","Photo":"home-1.jpg","Publier":"1"},
{"idHome":"2","Photo":"home2.jpg","Publier":"1"},
{"idHome":"3","Photo":"home3.jpg","Publier":"1"}]
var string = JSON.stringify(data);
var obj = $.parseJSON(string);
console.log(string);
var idHome = obj.idHome;
var photo = obj.Photo;
console.log(obj.idHome);
console.log(obj.Photo);
Problem with parsing json
console log :
[{"idHome":"1","Photo":"home-1.jpg","Publier":"1"},{"idHome":"2","Photo":"home-2.jpg","Publier":"1"},{"idHome":"3","Photo":"home-3.jpg","Publier":"1"}]
undefined
undefined
It is an array so you need to loop through, there are so many ways to do it.
for (i = 0; i < obj.length; i++) {
console.log(obj[i].idHome);
console.log(obj[i].Photo);
}
or:
obj.forEach(function(val) {
console.log(val.idHome);
console.log(val.Photo);
});
or:
for (var i in obj) {
console.log(obj[i].idHome);
console.log(obj[i].Photo);
}
Jquery use :
$.each(obj, function(_, val){
console.log(val.idHome);
console.log(val.Photo);
});
and so on....
Your json is an array of three objects.
Try
console.log(obj[0].idHome);
console.log(obj[0].Photo);
More info:
http://www.w3schools.com/json/json_syntax.asp