ajax / codeigniter out put create a new row every 4 columns - javascript

In the success part of my ajax each result gets put into columns.
What I am trying to achive is every 4 columns it will create a new row.
Question: On success part of ajax how to make it so every after every 4 columns will create a new row?
<script type="text/javascript">
$("#select_category").on('keyup', function(e) {
$.ajax({
type: "POST",
url: "<?php echo base_url('questions/displaycategories');?>",
data: {
category: $("#select_category").val()
},
dataType: "json",
success: function(json){
list = '';
list += '<div class="row">';
$.each(json['categories'], function(key, value ) {
list += '<div class="col-sm-3">';
list += value['name'];
list += '</div>';
});
list += '</div>';
$('.category-box').html(list);
}
});
});
</script>

You could just count how many you've added and insert a new row each time it reaches 4:
$("#select_category").on('keyup', function(e) {
$.ajax({
type: "POST",
url: "<?php echo base_url('questions/displaycategories');?>",
data: {
category: $("#select_category").val()
},
dataType: "json",
success: function(json) {
var list = '<div class="row">';
var index = 0;
$.each(json['categories'], function(key, value) {
list += '<div class="col-sm-3">';
list += value['name'];
list += '</div>';
index++;
if(index === 4) {
list += '</div><div class="row">';
index = 0;
}
});
list += '</div>';
$('.category-box').html(list);
}
});
});

Try this:
success: function(json){
list = '';
var cnt = 0;
list += '<div class="row">';
$.each(json['categories'], function(key, value ) {
list += '<div class="col-sm-3">';
list += value['name'];
list += '</div>';
cnt++;
if(!cnt%4){
list += '</div><div class="row">';
cnt = 0;
}
});
list += '</div>';
$('.category-box').html(list);
}

Related

dynamic select option and dynamic data from php

I tried develop add several selectbox dynamically and get data from selectbox my codes:
this codes add new selectbox and work
var y = 1;
var z = 1;
$('#add_kind').on('click', function () {
var html = '';
html += '<div class="prInput-row">';
html += '<select name="kind_id" class="halfselect kinds">';
html += '<option value="0">Kinds</option>';
html += '<?php foreach($kinds as $kind): ?>';
html += '<option value="<?php echo $kind->id;?>"><?php echo $kind->name;?></option>';
html += '<?php endforeach; ?>';
html += '</select>';
html += '<select name="kind_desc_id" class="halfselect kind_descriptions">';
html += '<option value="0">Kind Descriptions/option>';
html += '</select>';
html += '<input type="text" name="stock_piece" class="halfselect" placeholder="Stock Piece"/>';
html += '</div>';
$('#kind_area').append(html);
$('.kinds').each(function () {
$(this).attr('class', 'halfselect kinds_'+y);
y++;
});
$('.kind_descriptions').each(function () {
$(this).attr('class', 'halfselect kind_descriptions_'+z);
z++;
});
});
$('.kinds').each(function () {
$(this).attr('class','halfselect kinds_'+y);
y++;
});
$('.kind_descriptions').each(function () {
$(this).attr('class','halfselect kind_descriptions_'+z);
z++;
});
this codes get data from db and not work,
var i = 1;
$(".kinds_"+i).on('change', function() {
var kindID = $(this).val();
if(kindID) {
$.ajax({
type: "POST",
url: baseUrl+"products/getSelectedKind",
data: 'kind_id='+kindID,
success: function(data) {
$('.kind_descriptions_'+i).html(data);
}
});
} else {
$('.kind_descriptions_'+i).html('<option value="0">Kind Descriptions</option>');
}
i++;
});
how can change those codes and how can get dynamically datas
this picture my example
#anon, I solved thank you so much but 2 times write codes but how can write one time ?
$("#add_kind").click(function(){
$.each($("[class*='kinds_']"), function() {
$(this).on('change', function() {
var kindID = $(this).val();
var i = $(this).attr("class").substr(-1, 1);
if(kindID) {
$.ajax({
type: "POST",
url: baseUrl+"products/getSelectedKind",
data: 'kind_id='+kindID,
success: function(data) {
$('.kind_descriptions_'+i).html(data);
}
});
} else {
$('.kind_descriptions_'+i).html('<option value="0">Kind Descriptions</option>');
}
});
});
});
$.each($("[class*='kinds_']"), function() {
$(this).on('change', function() {
var kindID = $(this).val();
var i = $(this).attr("class").substr(-1, 1);
if(kindID) {
$.ajax({
type: "POST",
url: baseUrl+"products/getSelectedKind",
data: 'kind_id='+kindID,
success: function(data) {
$('.kind_descriptions_'+i).html(data);
}
});
} else {
$('.kind_descriptions_'+i).html('<option value="0">Kind Descriptions</option>');
}
});
});
you can get all element that have class started with "kinds_" with selector $("[class^=kinds_]") then do a loop to get your class index. So maybe something like this will work:
$.each($("[class^='kinds_']"), function() {
var selector = "."+$(this).attr("class");
$(document).on('change', selector, function() {
var kindID = $(this).val();
var i = $(this).attr("class").substr(-1, 1);
if(kindID) {
$.ajax({
type: "POST",
url: baseUrl+"products/getSelectedKind",
data: 'kind_id='+kindID,
success: function(data) {
$('.kind_descriptions_'+i).html(data);
}
});
} else {
$('.kind_descriptions_'+i).html('<option value="0">Kind Descriptions</option>');
}
});
})

wait for ajax function to finish until reload the function again using interval

I have an AJAX function to fetch data from the and append it to HTML every 1sec,the reason why I use AJAX is because I have a lot of data to fetch from the database so I need to fetch it with limit (100 data per-limit), so I refresh the AJAX function using interval, the problem is the data that shown is always the same because, before the function finish, the interval refresh the function again, is there any way to solve this problem?
JQuery AJAX code:
var ctr = 0;
var pct = 0;
var total = 0;
var bnprd = "<?php echo $bonperiod;?>";
var bnsrt = "<?php echo $bonsort;?>";
var mybonperiod = "<?php echo $mybonperiod;?>";
var sc = '000';
var interval;
window.onload = function () {
{getDataNoBreak();}
};
interval = window.setInterval(function () {getDataNoBreak()}, 0);} //set the interval
function getDataNoBreak() {
jQuery(document).ready(function() {
jQuery.ajax({
url: "{{ url('panel/bonus/payviasc/getDataNoBreak') }}",
type: 'POST',
data: {_token :'{{ csrf_token() }}',counter : ctr, bonperiod: bnprd, bonsort: bnsrt},
dataType: "json",
success: function(data) {
if(ctr==0){ total = data[0].total;}
for(var i =0; i < data.length; i++) {
if(data[i].loccd) sc = data[i].loccd;
else sc = '000';
var htm = '';
htm += '<tr>';
htm += '<td data-label="MEMBER">'+ data[i].dfno +' </td>';
htm += '<td data-label="MEMBER NAME">'+ data[i].fullnm +' </td>';
htm += '<td data-label="SC">'+ sc +' </td>';
htm += '<td data-label="PERIOD">'+ mybonperiod +' </td>';
htm += '<td data-label="GRADE">'+ data[i].level +' </td>';
htm += '<td data-label="BONUS">'+ data[i].totbns +' </td>';
htm += '<td data-label="SIGNATURE"> </td>';
htm += '</tr>';
$("#isi").append(htm);
pct += 1;
var totalPct = (pct/total)*100;
$("#progress".html('<div class="progress-bar progress-bar-striped active" style="width:' + totalPct + '%"></div>'));
$("#message").html('Loading data...');
if (totalPct == 100) {
completed();
}
}
if(ctr < total-1) ctr+=101;
}
,
error: function(data) {
}
});
});
}
function completed() { //when the interval is finish
$("#message").html("Completed");
if(pageBreak == 0){
$('#payviabank').DataTable({
"paging": true,
"lengthChange": false,
"searching": true,
"ordering": false,
"info": true,
"autoWidth": false
});
}
window.clearInterval(interval);
}
So first your interval is set to fire every 0 seconds, probably plays into it not working. However, what I think you want is to make another call on either success or complete. Just to simplify:
function makeRequest(payload){
var options = {
url : '/path/to/file.php',
type : 'POST',
data : payload,
success : function(res){
//do something with the (res)ponse, maybe make new payload
makeRequest(newpayload); //make the call again
}
}
$.ajax(options);
}
Of course, you may need to pass in extra parameters to the makeRequest function in order to make sure you don't get the same data again.
Set a timeout instead of an interval.
Then, in the "success" function of your ajax, set another timeout to run it again. That way you can guarantee it won't attempt to refresh again until the previous ajax request has finished.

Why is index never == 0?

<script>
var index = 0;
$.getJSON("./data/data.json", function(json) {
$.each(json, function(data) {
var html = "";
if(index == 0)
{
console.log(index + " first item");
html = "<div class='item active'>";
} else {
console.log(index + " its not 0");
html = "<div class='item'>"
}
console.log(json.length); // this will show the info it in firebug console
html += "<blockquote><div class='row'><div class='col-sm-3 text-center'><img class='img-circle' src='images/obama.jpg' style='width: 100px;height:100px;'></div><div class='col-sm-9'><p>Change will not come if we wait for some other person or some other time. We are the ones we've been waiting for. We are the change that we seek.</p><small>President Barack Obama</small></div></div></blockquote></div>";
$('body').append(html);
index++;
});
});
</script>
I need to generate 5 of these but the first one needs to be have 'item active'
If there is a better way, please let me know
Thank you for pointing out that my html was being overwritten. I updated my code but jQuery isn't actually placing my HTML into the body. so thats another question
You can add an index into the $.each method; this will span from 0 to data.length - 1
$.getJSON("./data/data.json", function(json) {
$.each(json, function(index, data) {
var html = "";
html += '<div class="item' + (index == 0 ? ' active' : '') + '">';
html += '<blockquote>...</blockquote>';
html += '</div>';
$('body').append(html);
});
});
<script>
var index = 0;
$.getJSON("./data/data.json", function(json) {
$.each(json, function(data) {
var html = "";
if(index == 0)
html = "<div class='item active'>";
else
html = "<div class='item'>";
html += "<blockquote><div class='row'><div class='col-sm-3 text-center'><img class='img-circle' src='images/obama.jpg' style='width: 100px;height:100px;'></div><div class='col-sm-9'><p>Change will not come if we wait for some other person or some other time. We are the ones we've been waiting for. We are the change that we seek.</p><small>President Barack Obama</small></div></div></blockquote></div>";
$('body').append(html);
index++;
});
});
</script>

Update html table according to ajax json response

i have a JSON response like below
{
"Parent": "skystar",
"Children": [
{"Name":"MW"},
{"Name":"PR"},
{"Name":"PV"},
{"Name":"ST"}
]
},
{
"Parent": "RR",
"Children": [
{"Name":"RC"},
{"Name":"RP"}
]
}
Now i need to bind this to the table.
i tried to call AJAX like below
$.ajax({
url: 'echo/sample.json/',
success: function (response) {
var trHTML = '';
$.each(response, function (i, item) {
trHTML += '<tr><td>' + item.Children + '</td>';
});
$('#records_table').append(trHTML);
}
});
But i am not able to bind the table
what i am doing wrong??
JSFIDDLE
one more thing every children has hypher link how to add it
How to do that in Jquery or javascript??
Any help??
Demo: http://jsfiddle.net/tqyn3/336/
var jsonData = '[{"Parent":"skystar","Children":[{"Name":"MW"},{"Name":"PR"},{"Name":"PV"},{"Name":"ST"}]},{"Parent":"RR","Children":[{"Name":"RV"},{"Name":"RP"}]}]';
$.ajax({
url: '/echo/json/',
type: 'POST',
data: {
json: jsonData
},
dataType:'json',
success: function (response) {
var trHTML = '';
$.each(response, function (i, item) {
//alert(item.children);
$.each(item.Children, function(j, child) {
trHTML += '<tr><td>' + child.Name + '</td>';
});
});
$('#records_table').append(trHTML);
}
});
Please see following JSFiddle http://jsfiddle.net/s701aduz/
var jsonData = '[{"Parent":"skystar","Children":[{"Name":"MW"},{"Name":"PR"},{"Name":"PV"},{"Name":"ST"}]},{"Parent":"RR","Children":[{"Name":"RV"},{"Name":"RP"}]}]';
$.ajax({
url: '/echo/json/',
type: 'POST',
data: {
json: jsonData
},
dataType:'json',
success: function (response) {
var trHTML = '';
$.each(response, function (i, item) {
trHTML += '<tr>';
$.each(item.Children, function(j, child) {
trHTML += '<tr><td>' + child.Name + '</td>';
});
trHTML += '</tr>';
});
$('#records_table').append(trHTML);
}
});
The problem you had was that item.Children was an array itself so when you included that in the string it would simply output [object Object], you have to iterate over the children as well. Also make a row for each element in the response and a td for each child, or at least I'm guessing that's what you were intending.
var json_data = $.parseJSON(response);
var table = $('<table>');
$.each(json_data,function(index,obj){
var tr = $('<tr>');
$.each(obj.Children,function(_index,_children){
var td = $('<td>');
$(td).text(_children.Name);
$(tr).append(td);
})
$('#records_table').append(tr);
});
var jsonData = [{"Parent":"skystar","Children":[{"Name":"MW"},{"Name":"PR"},{"Name":"PV"},{"Name":"ST"}]},
{"Parent":"RR","Children":[{"Name":"RV"},{"Name":"RP"}]}
];
$.each(jsonData, function (i, item) {
if(i == 0) {
$('#records_table').find('th:first').html(item.Parent);
} else {
$('#records_table').find('th:last').after('<th>'+ item.Parent +'</th>');
}
$.each(item.Children, function(j, child){
if(i==0) {
var tr = $('<tr />');
var td = $('<td />');
$(td).text(child.Name);
$(tr).append(td);
$('#records_table').append( tr );
} else {
var td = $('<td />');
$(td).text(child.Name);
$('#records_table').find('tr:eq('+(j+1)+')').append( td );
}
})
});
Check it will help you
http://jsfiddle.net/tqyn3/338/

Pulling in JSON via AJAX to populate a Drop-Down

I am pulling in some JSON data that will vary... for instance:
Data returned could be:
[{"userID":"2779","UserFullName":" Absolute Pro-Formance"},{"userID":"2780","UserFullName":" AR Fabrication"},{"userID":"2781","UserFullName":" Banda Lucas Design Group"}]
or:
[{"orderID":"112958","OrderName":"Order ID: 112958"},{"orderID":"112957","OrderName":"Order ID: 112957"},{"orderID":"112956","OrderName":"Order ID: 112956"}]
What I am attempting to do is process this JSON to build a <select> list.
// Load in a drop-down as JSON
function LoadDropDown($url, $where, $id, $selectName){
var $loading = '<div class="pageLoader" style="margin:0 auto !important;padding:0 !important;"><img src="/assets/images/ajax-loader.gif" alt="loading..." height="11" width="16" /></div>';
var $t = Math.round(new Date().getTime() / 1000);
var $container = jQuery($where);
var options = {
url: $url + '?_=' + $t,
cache: false,
type: 'POST',
beforeSend: function(){
$container.html($loading);
},
success: function(data, status, jqXhr){
$html = '<select class="form-control" id="'+$selectName+'" name="'+$selectName+'">';
$html += '<option value="0">- Select an Option -</option>';
for(var i = 0; i < data.length-1; ++i) {
var item = data[i];
console.log(item.userID);
}
$html += '</select>';
$container.html('<pre>' + data + '</pre>');
},
complete: function(jqXhr, status){},
error: function(jqXhr, status, error){
$container.slideDown('fast').html('<div class="alert alert-danger alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button><i class="fa fa-exclamation-triangle fa-4x pull-left"></i><p><strong>Danger Will Robinson!</strong><br />There was an issue pulling in this page. Our support team has been notified, please check back later.</p></div>');
}
};
jQuery.ajax(options);
}
The issue I am having is... #1 console.log(item.userID); always shows undefined, and #2 how can I effecitvely dynamically build the options? The returned JSON will ALWAYS contain 2 items per row and id, and a name
UPDATE
for(var $key in data){
var $val = data[$key];
for($j in $val){
console.log('name:' + $j + ' = ' + $val[$j]);
}
}
Is showing me what I need in Firefox Console... But 1 item per line, for each (for example the 1st JSON) name:userID = 1234 next line name:UserFullName = TheName
How can I get them so I can build my <options>?
With:
for(var k in data) {
console.log(k, data[k]);
}
I am returned:
2955 Object { orderID="8508", OrderName="Order ID: 8508"}
and
2955 Object { userID="1355", UserFulleName="Me Myself And I"}
You don't need to use such messy code. Also in your Ajax setup dataType:"json"
success:function() {
var listB=$('#yourdropdownId');
listB.empty();
$.each(result, function (index, item) {
listB.append(
$('<option>', {
value: item.userID,
text: item.UserFullName
}, '<option/>'))
});
}
Also the $.getJson instead of ajax if you only want retrieve json from server
$.getJSON('#Url.Action(" "," ")',
{ "youparametername": yourdata}, function (data) {
$.each(data, function (index, item) {
})
});
inside the options object, make sure to use the
dataType: 'json'
Or in the success handler you can use
JSON.parse(data)
Cured: Changed my loop to cycle through each item in the returned JSON, got their keys, etc...
var $dl = data.length;
for(var $i = 0; $i < $dl - 1; ++$i) {
var $keys = Object.keys(data[$i]);
$html += '<option value="' + data[$i][$keys[0]] + '">' + data[$i][$keys[1]] + '</option>';
}

Categories

Resources