How to iterate multiple json data in jquery response - javascript

I am getting multiple data from my JSON response like below.
WellNames […]
0 {…}
id 56
well_name AL HALL
api 34005205550000
1 {…}
id 498
well_name BONTRAGER
api 34005233850000
2 {…}
id 499
well_name BONTRAGER
api 34005233860000
I just want to iterate all data and append in select box having id result
i tried below code but getting undefined value in select tags.Please help me to display this values in my select tag.
Below is my jquery code
<script type="text/javascript">
$("#clientname").on('change', function() {
ajaxRequest = $.ajax({
url: '<?= Router::url(['controller' => 'Orders', 'action' => 'getWelldetails']) ?>',
type: 'POST',
data: {clientId: $("#clientname").val()},
dataType: "json",
success: function(response) {
$(response).each(function () {
$("<option value='" + response['id'] + "'>" + response['well_name'] + "</option>").appendTo('#result');
});
},
error: function(response) {
}
});
});
</script>

You need to loop through the WellNames property of your result, not on your result itself.
Also, you're not using jQuery each properly. Either use $.each or use a for loop:
for(let item of response.WellNames) {
$("<option value='" + item.id + "'>" + item.well_name + "</option>").appendTo('#result');
}

Yes its done from below changes which i forgot to write
$(response.WellNames).each(function (i,value) {
$("<option value='" + value['id'] + "'>" + value['well_name'] + " - " + value['api'] + "</option>").appendTo('#result');
});

You need iterate on *WellNames* property of your response.
Use hasOwnProperty so that you don't iterate on undefined property.
I will not suggest to add elements directly to control in a loop. So create an array containing html of and then add it to the control.
var arrHtml = [];
for (var item of response.WellNames) {
if (response.WellNames.hasOwnProperty(item)) {
arrHtml.push("<option value='" + item.id + "'>" + item.well_name + "</option>");
}
}
$('#result').innerHtml = arrHtml.join();

Related

PHP generated option list only appearing on first Ajax dynamically generated container

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");
}

Update: How do I dynamically populate a list with data from a JSON file?

I want to dynamically populate a list with elements from a JSON file. The idea is to switch the test_ID in the list with the actual object from the JSON file. How do I do this?
JSON file
[
{
"id": "a",
"test": "Java",
"testDate": "2016-08-01"
},
{
"id": "b",
"test":"JavaScript",
"testDate": "2016-08-01"
}
]
jQuery
$(function(){
$.ajax({
type : 'GET',
url : 'json/data.json',
async : false,
beforeSend : function(){/*loading*/},
dataType : 'json',
success : function(result) {
});
$("#test_ID").empty(); //emtpy the UL before starting
$.each(arr_json, function(i, v, d) {
$("#test_ID").append("<li id='" + v.id +'" + v.test +"' >" + v.testDate + "<li>");
});
}
});
});
HTML
<li id="test_ID"></li>
I do receive a couple of errors. The Line:
$("#test_ID").append("<li id='" + v.id +'" + v.test +"' >" + v.testDate + "<li>");
gives the following error: invalid number of arguments and unclosed String literal.
I am also unsure of how to identify to specific elements in the JSON file.
Update
I would like if the list element was in this format "Java 2016-08-01" and "JavaScript 2016-08-01". Thank you!
You have a couple of errors in your javascript. See the corrected version below:
$(function(){
$.ajax({
type : 'GET',
url : 'json/data.json',
async : false,
beforeSend : function(){/*loading*/},
dataType : 'json',
success : function(result) {
$("#test_ID").empty(); //emtpy the UL before starting
// **************** correction made to the line below ***********************
$.each(result, function(i, v, d) {
// **************** correction made to the line below ***********************
$("#test_ID").append('<li id="' + v.id + '">' + v.test + ' ' + v.testDate + '</li>'); // correction made here
});
}
});
});
I did a quick fiddle. I don't quite understand what you're doing with v.test being unmarked inside the HTML tags so I did not include it. I used minimal JQuery to avoid complexity.
https://jsfiddle.net/ndx5da97/
for (record in data) {
$("#test_ID").append('<li id="' + data[record].id + '">' + data[record].testDate + '</li>');
}
Hope this helps!

Populating JSON array to drop down reserved word column name conflict

This is the first time ill use JSON. I used the json_encode(myarrayhere) to return array value as shown below.
There is a corresponding value on change of selected value on dropdown.
I verified that I get the array data by using alert(dataArray) and it returns like this
[{"title":"First"},
{"title":"Second"},
{"title":"Third"} ]
I used the word title as column name for a table I'm using in my database.
But the problem now is how to properly populate them in a drop down. I tried to do value.title but it looks like that title is a reserved word/method in php
$.ajax({
type: 'POST',
data: {ctgy: selected},
url: 'awts.php' ,
datatype: 'json',
success: function (dataArray) {
alert(dataArray);
var items = '';
$.each(result,function(name,value) {
items += "<option value='"+value.title+"'>"+value.title)+"</option>";
});
$("#dropdownselectid").html(items);
}
});
Thanks in advance.
Firstly, if you check the console you'll see that you have a syntax error. You have an extra ) when you append value.title to the HTML string.
Secondly, your $.each() call is attempting to loop through result when your data is in a variable named dataArray.
Try this:
$.ajax({
type: 'POST',
data: { ctgy: selected },
url: 'awts.php',
datatype: 'json',
success: function(dataArray) {
var items = '';
$.each(dataArray, function(name, value) {
items += '<option value="' + value.title + '">' + value.title + '</option>';
});
$("#dropdownselectid").html(items);
}
});
Working example

Concat parameter syntax

Not sure how to even ask the question, if any suggestions for the title please let me know...
I have the following function that retrieves via AJAX information of a JSON file. This function as you can see below:
setOptionsSettings("[data-machine-brand-options]", apiUrlMachineBrands, 'name');
function setOptionsSettings(htmlElement, url, apiParameter) {
$.ajax({
dataType: "json",
url: url,
// CREATE GENERIC SOLUTION for the spinner
beforeSend: function(xhr) {
$('main').html('<div class="spinner"><div class="hori-verti-centering"><div class="bounce bounce1"></div><div class="bounce bounce2"></div><div class="bounce bounce3"></div></div></div>');
setHeader(xhr);
},
success: function (data) {
$.each(data, function(i) {
$(htmlElement).append("<option id=" + data[i].id + " value=" + data[i].apiParameter + ">" + data[i].apiParameter + "</option>");
});
}
});
return {};
}
I'm trying to set apiParamter so when you call the function setOptionSettings you can place the name of the parameter you need to call. So in this case the parameter is name. How can I insert this into the function so it works?
I tried the following and other solutions but nothing would work, any suggestions?
$(htmlElement).append("<option id=" + data[i].id + " value=" + data[i]. + apiParameter + ">" + data[i]. + apiParameter + "</option>");
To access object property using string key use Bracket notation i.e data[i][apiParameter]
As you are using jQuery create element using it.
$(htmlElement).append($('<option></option>', {
"id": data[i].id,
"value": data[i][apiParameter]
}));

How to retrieve a value of a selected Item from a dropdown List?

How to i get a value of a selected ITEM from a drop down list ? I'm reading my values a SQL Table using a Stored Procedure ,Once the list is populated i want to take the selected ITEM and save the SQL TABLE. Any help will be much appreciated. Here is what i've tried :
function QueryKomaxDetails() {
$.ajax({
url: GET_SCHEDULE_DEPARTMENTS,
data: 'includeInactive=' + null,
dataType: 'json',
success: LoadKomaxDetails
});
}
var LoadKomaxDetails = function (data) {
var dllItems = eval(data);
var komaxDetails = $("#ddlItems").val();
$.each(dllItems, function () {
komaxDetails.append("<option value='" + this.departmentId + "'>" + this.departmentName + "</option>");
});
}
And i managed to get ITEM as a dropdown list.
Here is my HTML code as follows :
<label>Select Komax :</label><select id="ddlItems" name="komax" ></select>
Try this,
var komaxDetails = $("#ddlItems");
$.each(dllItems, function () {
komaxDetails.append("<option value='" + this.departmentId + "'>" + this.departmentName + "</option>");
});

Categories

Resources