Generate multiple HTML elements from JSON using Jquery? - javascript

How to use Jquery and Javascript to extract JSON from $ajax and then do a foreach, and create a string that will append to html DOM?
Something like:
$(document).ready(function (e) {
$.ajax({
type: "POST",
url: "Companies/GetSearchRatios",
context: this,
success: function (data) {
//return JSON
}
});
Result JSON
[{"name":"MyNAme","value":350},{"name":"Hello","value":356}]
I can easily acces this values inside $ ajax method success, but how can I extract this value outside of method and use it to append to DOM?
This is what I need as a result of some for/foreach method:
var $gElemRatios =
'<option value=""></option>' +
'<option value="350">MyNAme</option>' +
'<option value="356">Hello</option>';
Then I use this var to combine with another:
var $gElem =
'<div class="cbox cboxQuarterWidth">' +
'<select id="combobox_0">' +
$gElemRatios + // here I add previous generated elem
'</select>' +
'</div>';
And finally:
$("#main").append($gElem);
Any ideas?

You can use $.each to loop through the data passed to the success handler:
$.ajax({
type: "POST",
url: "Companies/GetSearchRatios",
context: this,
success: function (data) {
$.each(data,function(){
console.log(this.name); //just an example how to access things
$('#select').text(this.value); //maybe?
});
}
});
See this fiddle

Related

how to set dynamic data in var a

I want to get dynamic data in one <div id = "view"> </div>
I use ajax to take dynamic data from api and insert it with var a. I will try to describe with code what I want to get exactly
$.ajax({
url:'url', // [{id:"1",name:"name1"},{id:"2",name:"name2"},{id:"3",name:"name3"}];
method: 'get',
dataType: "json",
success: function (data) {
data.forEach(function(elem){
var a = "ID: " elem.id +"<b>" + elem.name"</b> ";
})
$('#view').html(a);
}
});
Here you are getting the result in a foreach loop which means "a" contains all the results returned by the ajax call, in order to show only one result in a single div we would need to put the value of each loop call in the div, one way is to append the div for each result inside a parent div. I have modified your code below hopefully it helps.
HTML:
<div id = "dataholder"> </div>
JS:
$.ajax({
url:'url', // [{id:"1",name:"name1"},{id:"2",name:"name2"},{id:"3",name:"name3"}];
method: 'get',
dataType: "json",
success: function (data) {
var j = 1;
data.forEach(function(elem){
var a = "ID: " elem.id +"<b>" + elem.name"</b> ";
var view_div_id = "view-"+j;
$( "#inner" ).append( "<div id ="+ view_div_id +"> </div>" );
$('#view-'+j).html(a);
j++;
})
}
});

Jquery append after ajax not working every time

I have a problem with jquery append. This is the code:
$.ajax({
method: "POST",
url:
"/getcars.php",
data: {
model_car: sessionStorage.getItem("model")
}
}).done(function(msg) {
var obj = JSON.parse(msg);
$("#model").empty().append('<option value="-1">Model</option>');
var string_option = "";
Object.keys(obj.model).forEach(function(key) {
string_option += '<option value="' + obj.model[key] + '">' + obj.model[key] + '</option>';
});
console.log(string_option);
$("#model").append(string_option);
})
This code work very well, but not every time. (only the append option not working. This: console.log(string_option) it`s ok every time).
Can you help me, please?
Thank you!!
Looks like you need to put the code to be executed after the document is fully loaded using the "$( document ).ready" jQuery event
$( document ).ready(function() {
$.ajax({
method: "POST",
url:
"/getcars.php",
data: {
model_car: sessionStorage.getItem("model")
}
}).done(function(msg) {
var obj = JSON.parse(msg);
$("#model").empty().append('<option value="-1">Model</option>');
var string_option = "";
Object.keys(obj.model).forEach(function(key) {
string_option += '<option value="' + obj.model[key] + '">' + obj.model[key] + '</option>';
});
console.log(string_option);
$("#model").append(string_option);
})
});
You can learn more about this on the below link
https://api.jquery.com/ready/
Try to check the response on Ajax success sometimes it happens due to malformed JSON is sent back with a 200/OK
One possible problem could be that you run the .append() before DOM is loaded. If this is the problem you can try 2 methods:
put this javascript code inside footer.
add to your code:
$(document).ready(function(){
//... your ajax request
})

how to display array passed via ajax in html

This is my ajax:
$("#submit").on("click",function()
{
$("#add_car_form").submit(function(){
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "text",
url: "add_car_submit.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
$(".the-return").html("<br />JSON: " + data );//this outputs
{"car_name":";ll","car_maker":"njk","car_type":"nkj","passanger":"1","rate":["89","67","45","34","23"],"action":"test"}
}
});
document.getElementById("add_car_form").reset();
return false;
});
});
I simply echo from php script like this: echo $return["json"]; and it will output like this:
{"car_name":";ll","car_maker":"njk","car_type":"nkj","passanger":"1","rate":["89","67","45","34","23"],"action":"test"}
How do append to a div in html table form like this?
Car Name: name
Car Maker: maker
......
try this in your success function
data = jQuery.parseJSON( data ); //parse data if this is text other wise use data directly. hope this is a text param in your case.
var out = '<table>';
$.each(data, function( key, value ) {
out += '<tr><td>'+key+': '+ value +'</td></tr>';
});
out += '</table>';
//append out to your div
$(".the-return").html(out);
You should not create a form submit handler inside a click handler as it could create multiple listeners for single click event.
I think you could just encode the data use json_encode in the server side then, accept the response as json in the client using dataType: 'json' then
$("#submit").on("click", function () {
var $form = $("#add_car_form")
var data = {
"action": "test"
};
data = $form.serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "add_car_submit.php", //Relative or absolute path to response.php file
data: data,
success: function (data) {
$(".the-return").html("Car Name" + data.car_name + '<br />Car Maker' + data.car_maker); //Add more properties here
}
});
document.getElementById("add_car_form").reset();
return false;
});

how to clean option values under select - html tag

I am using two drop down(first drop-down category and second drop-down sub category) in a page,both drop-down will be loaded dynamically, in which I will be selecting a value from first drop-down accordingly I have to load value to second drop-down.I has done that,but thing is that it will get done for first time.
But when I click on some other option in states drop-down, its not getting updated on second drop-down.
And My code is:
This piece of code is to get list of category while loading page ie under document.ready
$.ajax({
url : "../category/getCategory",
type : "post",
contentType : "application/json",
dataType : "json",
success : function(data) {
var categoryBOs = data.categoryBOs;
$.each(categoryBOs, function(key, value) {
$("#productCategory").append(
'<option value='+value.categoryId+'>'
+ value.categoryName
+ '</option>');
});
}
});
This part of ajax is to load sub category
$("#productCategory").on('change', function() {
alert($(this).val());
$.ajax({
url : "../category/getSubCategory",
type : "post",
cache : false,
dataType : "json",
data : "categoryId=" + $(this).val(),
success : function(data) {
var subCategoryBOs = data.subCategoryBOs;
$.each(subCategoryBOs, function(key, subCategoryBO) {
subCategories.push({lable:subCategoryBO.categoryId , value:subCategoryBO.categoryName});
$("#productSubCategory").append(
'<option value='+subCategoryBO.categoryId+'>'
+ subCategoryBO.categoryName
+ '</option>');
});
}
});
});
From what I see in your code you always append new entries, yet never remove old ones before. So possibly your list just keeps getting longer with new entries at its end? Try to remove the entries before append new ones:
$("#productSubCategory option").remove();
$("#productSubCategory").append(
'<option value=' + subCategoryBO.categoryId + '>' + subCategoryBO.categoryName + '</option>');
In my experience $.each with $.append can get very slow at some amount of list entries. I would rewrite it in native javascript with for() and createElement().
Try adding $("#productCategory").empty() before the first $.each and $("#productSubCategory").empty() before the second $.each.
you need to make html in .each and append after .each end. No option change from first drop down you need to remove the previous on by using $("#productSubCategory option").remove();
$.ajax({
url: "../category/getCategory",
type: "post",
contentType: "application/json",
dataType: "json",
success: function (data) {
var categoryBOs = data.categoryBOs;
var html = '';
$.each(categoryBOs, function (key, value) {
html += '<option value=' + value.categoryId + '>' + value.categoryName + '</option>';
});
$("#productCategory").append(html);
}
});
$("#productCategory").on('change', function () {
alert($(this).val());
$.ajax({
url: "../category/getSubCategory",
type: "post",
cache: false,
dataType: "json",
data: "categoryId=" + $(this).val(),
success: function (data) {
var subCategoryBOs = data.subCategoryBOs;
var html = '';
$.each(subCategoryBOs, function (key, subCategoryBO) {
subCategories.push({ lable: subCategoryBO.categoryId, value: subCategoryBO.categoryName });
html += '<option value=' + subCategoryBO.categoryId + '>' + subCategoryBO.categoryName + '</option>';
});
$("#productSubCategory").append(html);
}
});
});
Just simple thing you have to do here is that every time when you load sub-categories just place following before that .
$(dropdown).empty();
Thanks !
$("select#catname").change(function () {
// part of code
$("#subcatname").append($newOpt1);
// appending the category of dropdown
}
$("#subcatname").trigger('contentChanged');
// changing the contenet
}
});
$("select#subcatname").change(function () {
// something changes after trigger in dropdown
});
// removing the content or clearing the content after selecting
$("#subcatname").empty();
});
});

select isn't populating from JSON data

I'm having trouble with the following code.
The JSON data seems to be generated properly and the select field is being emptied of existing options as I expect it should, however, the options generated from the JSON data are not being appended to the select.
I'm not getting a console error and I am not seeing what why it's not appending.
Any suggestions?
<script>
$('#campReg').change(function() {
var $self = $(this);
$.ajax ({
url: 'php/getCamps.php',
data: { id : $self.val()},
dataType:'JSON',
type:'POST',
success: function(data){
var sel = $('#otherCamps').empty();
var toAppend = '';
$.each(data,function(i,data){
toAppend += '<option value="'+data.id+'">'+data.desc+'</option>';
});
$('#sessions').append(toAppend);
}
})
});
</script>
The JSON:
{data: [{id:1, desc:06/09 - 06/13 - WEATHER}, {id:3, desc:08/01 - 08/04 - TEST CAMP}]}
Here is the Working Fiddle:
Make these two changes to your code:
$.each(data.data,function(i,data){
and
$('#otherCamps').append(toAppend);
So your code will be:
$('#campReg').change(function() {
var $self = $(this);
$.ajax ({
url: 'php/getCamps.php',
data: { id : $self.val()},
dataType:'JSON',
type:'POST',
success: function(data){
$('#otherCamps').empty();
var toAppend = '';
$.each(data.data,function(i,data){
toAppend += '<option value="'+data.id+'">'+data.desc+'</option>';
});
$('#otherCamps').append(toAppend);
}
})
});
I think success: function(data) receives the whole json object in data, but it has a data property that holds the actual array. So you have to iterate over data.data: $.each(data.data, ...
Based on your comment, you need to use:
$('#otherCamps').append(toAppend);
instead of:
$('#sessions').append(toAppend);
since you've assigned id="otherCamps" to your select element.

Categories