I have div where I need to show some data
I have button. By button I show modal
Here is code of modal
<div class="modal fade" id="myModal" role="dialog" data-backdrop="false">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Создание вопроса</h4>
</div>
<div class="modal-body">
#Html.Partial("~/Views/Questions/CreateQuestion.cshtml")
</div>
</div>
</div>
Here is code of script
<script>
var myFormDialog = $("containerForPartialView").dialog(
{ autoOpen: false, modal: true });
$("myButtonForShowDialog").button().on("click", function () {
myFormDialog.dialog("open");
});
$('.click').on('click', function () {
$('.content').toggle();
});
var counter = 0;
$(document).ready(function () {
$('#save').click(function () {
save();
email_update();
});
});
function save()
{
$.ajax({
type: 'Post',
dataType: 'Json',
data: {
question1: $('#Question1').val(),
question2: $('#Question2').val(),
question3: $('#Question3').val(),
question4: $('#Question4').val(),
question5: $('#Question5').val(),
question6: $('#Question6').val(),
question7: $('#Question7').val(),
question8: $('#Question8').val(),
question9: $('#Question9').val(),
question10: $('#Question10').val(),
},
url: '#Url.Action("Index", "Questions")',
success: function (da) {
if (da.Result === "Success") {
window.location.href = da.RedirectUrl;
} else {
alert( 'Error'+ da.Message);
}
},
error: function (da) {
alert('Error');
}
});
}
Also I have script for saving and updating div
Here is code
<script>
$(document).ready(function () {
email_update();
});
function email_update() {
$.ajax({
url: '#Url.Action("QuestionsList", "Questions")',
contentType: 'application/json; charset=utf-8',
type: 'GET',
dataType: 'json',
processData: false,
success: function (result) {
var email = result;
var edit = '#Url.Content("~/Images/Edit.png")';
var delete_ = '#Url.Content("~/Images/Delete.png")';
// console.log(result[0].Name);
for (var i = 0; i <= email.length - 1; i++) {
var arrow = '#Url.Content("~/Images/plus_plus.png")';
var questionHtml = '<div class = "title" style="margin-top:15px;margin-left:15px;margin-bottom:10px;">'
+
'<img class="click" src="'
+ arrow
+ '">' +
'<span class="test">' +
'<input type="text" class="testclass" readonly value="' +
result[i].Quest + '">' +
'<a style="margin-left:25px;">' +
'<img src="' + edit + '"/>' +
'<img style="margin-left:10px;" src="' + delete_ + '"/>' +
'</div>' +
'<div class ="content" style="margin-left:60px; width: 80%; height: 100px; background: white;">' +
'<div style="width: 100%">' +
'<div style="float:left; width: 50%;">' +
'<b style="margin-left: 40px;">' + "Время на ответ" + '</b>' +
'<b>' + ":" + '</b>' +
'<span>' + "Время на подготовку" +'</span>'+
'</div>' +
'<div style="float:right; width: 50%;">' +
'<b>' + result[i].TimeForAnswer + '</b>' +
'<b>' + ":" + '</b>' +
'<b>' + result[i].TimeForReady + '</b>'+
'</div>' +
'</div>' +
'</div>';
$(".count").append(questionHtml);
}
}
});
}
|
It works well when page starts. But in modal it not works, I mean this code email_update(); .
Related
<script>
$.ajax({
method: "POST",
url: "API/actions/getAllCategories",
async: false,
success: function(msg) {
newdiv = "";
var count = 1;
msg.forEach(function(row) {
if (count == 1) {
newdiv += ' <li class="active">' +
'<a data-toggle="tab" href="#tab' + count + '" aria-expanded="true">' +
'<span>' + row.name + '</span>' +
'</a>' +
'</li>';
} else {
newdiv += ' <li>' +
'<a data-toggle="tab" href="#tab' + count + '" aria-expanded="true">' +
'<span>' + row.name + '</span>' +
'</a>' +
'</li>';
}
$.ajax({
method: "POST",
url: "API/actions/getProductsbycatId",
async: false,
data: {
"categoryId": row.id,
"countryId": `<?php echo $_SESSION['evoucher']['countryId'] ?> `
},
success: function(msg1) {
var active = '';
if (count == 1) {
active = "active in";
}
newdiv1 = ' <div id="tab' + count + '" class="tab-pane fade ' + active + '">' +
' <div class="bbb_viewed">' +
' <div class="row">' +
' <div class="col">' +
' <div class="bbb_main_container">' +
' <div class="bbb_viewed_title_container">' +
' <div class="bbb_viewed_nav_container">' +
' <div class="bbb_viewed_nav bbb_viewed_prev"><i class="fas fa-chevron-left"></i></div>' +
' <div class="bbb_viewed_nav bbb_viewed_next"><i class="fas fa-chevron-right"></i></div>' +
' </div>' +
' </div>' +
' <div class="bbb_viewed_slider_container">' +
' <div class="owl-carousel owl-theme bbb_viewed_slider">';
msg1.forEach(function(row1) {
newdiv1 += ' <div class="owl-item">' +
' <div class="bbb_viewed_item1 discount d-flex flex-column align-items-center justify-content-center text-center">' +
' <div class="bbb_viewed_image"><img src="' + row1.pathimage2 + '" alt=""></div>' +
' <div class="bbb_viewed_content text-center">' +
' <div class="bbb_viewed_name">' + row1.name + '</div>' +
' </div>' +
' </div>' +
' </div>';
})
newdiv1 += ' </div>' +
' </div>' +
' </div>' +
' </div>' +
' </div>' +
' </div>' +
'</div>';
$("#tabs").append(newdiv1);
},
error: function(error) {
alert("error");
}
})
count++;
})
$("#bestsellernav").html(newdiv);
},
error: function(error) {
alert("error");
}
})
</script>
I am making an AJAX call to different APIs and I am making many ajax calls at the same time but I am getting this error in my console.
Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects for the end user’s experience.
I think it is related to async:false, but I can't get rid of it because my page is not staying the way it is. Any alternatives for async:false?
I am trying to implement datatables draw() method in my Django application using AJAX. I have implemented both datatables and AJAX, which are working fine. However, I am facing a lot of challenges anytime I create a new object and call the draw() method so that datatables can refresh the table and show the newly created data the proper way. If I add the draw() method, the table does not get populated at all except I refresh the page.
main.js
//datatables
$(document).ready(function() {
$('table').on('click', ".dropdownDatatableButton" ,function() {
$( this ).toggleClass( "active");
});
function csrfSafeMethod(method) {
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
};
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
var csrftoken = jQuery("[name=csrfmiddlewaretoken]").val();
var table = $('#boardsTable').DataTable({
"autoWidth": false,
"info": false,
"lengthChange": false,
"processing": true,
"hover": true,
"serverMethod": 'post',
"searching": true,
"ajax": "/boards/api/data/?format=datatables",
"pagingType": "full_numbers",
"order": [[ 0, "asc" ]],
language: {
search: "",
"zeroRecords": '<img class=' + '"dataTables-error-image"' + 'src=' + "'/static/media/images/empty-search.jpg'"
+ '/>' + '<p class=' + '"dataTables-error-text"' + '>'
+ 'No boards were found that match your search' + '<p/>',
"loadingRecords": '<div class="spinner-border m-5" role="status">'
+ '<span class="sr-only d-block">Loading...</span> </div>'
+ '<p class="d-block text-center mt-3">Pulling board information...' + '</p>',
"processing": '<p class="d-block text-center datatables-processing-text">Please wait...' + '</p>',
"emptyTable": '<img class=' + '"dataTables-error-image"' + 'src=' + "'/static/media/images/new.jpg'"
+ '/>' + '<p class=' + '"dataTables-error-text font-weight-bold"' + '>'
+ 'No boards to show right now' + '<p/>'
+ '<p class=' + '"dataTables-empty-table-description"' + '>'
+ 'When you start working on recruitment campaigns, we’ll list all your boards here.'
+ '<p/>'
+ '<a class="dataTables-error-create-btn show-only-on-mobile" data-bs-toggle="modal"'
+ 'data-bs-target="#createBoardModal" data-bs-backdrop="static"'
+ 'data-bs-keyboard="false">' + 'Create a board' + '<a/>',
},
initComplete : function() {
$("#boardsTable_filter").detach().appendTo('.filter-form');
},
"drawCallback": function(settings) {
var pagination = $(this).closest('.dataTables_wrapper').find('.dataTables_paginate');
pagination.toggle(this.api().page.info().pages > 1);
},
"columns": [
{data: null,
render: function ( data, type, row ) {
// show the board avatar and make merge it with `data: name`
return '<a class="datatable-board-link" href="' + data.url.toLowerCase() + '/manage' + '">'
+ '<img class="datatable-board-link-img" ' + 'src="' + data.avatar + '" ' + 'width="30px" '
+ 'height="30px" ' + 'alt="board avatar" />' + data.name + '</a>' ;
}
},
{data: null,
render: function ( data, type, row, meta ) {
// show the URL which are accessible to candidates
return '<a class="new-tab-board-link" href="' + data.lead.username + '/'
+ data.url + '" target="_blank">' + '/' + data.url
+ '<span class="material-icons">open_in_new</span>' + '</a>';
}
},
{ data: "lead",
render: function ( data, type, row, meta ) {
// show the lead recruiter avatar and combine the first and last names into a single table field
return '<a class="datatable-profile-link"' + 'href="'
+ 'http://127.0.0.1:8080/people/teams/' + data.id + '/' + data.username.toLowerCase() +'"'
+ 'target="_blank"' + '>' + '<img class="datatable-profile-link-img" ' + 'src="'+ data.avatar
+ '" ' + 'width="30px" ' + 'height="30px" ' + 'alt="' + data.name + ' ' + "'s avatar" + '"'
+ '/>' + data.name + '</a>';
},
},
{ data: null,
render: function ( data, type, row, meta ) {
return '<div class="dropdown datatables-dropdown" id="datatablesDropdown">'
+ '<span class="material-icons btn dropdownDatatableButton" id="dropdownDatatableButton"'
+ 'type="button"' + 'data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">'
+ 'more_horiz</span>'
+ '<div class="dropdown-menu dropdown-menu-right datatables-dropdown-inner"'
+ ' aria-labelledby="dropdownDatatableButton">'
+ '<ul>'
+ '<li>Board settings</li>'
+ '<li><a class="btn btn-link btn-sm text-left">Delete</a></li>'
+ '</ul>'
+ '</div>'
+ '</div>';
},
},
],
"columnDefs": [
{"width": "10%", "targets": 3, "orderable": false},
],
});
table.columns().iterator('column', function (ctx, idx) {
$(table.column(idx).header()).append('<span class="sort-icon"/>');
});
// call the AJAX post method
$("#createBoardViaModalForm").on('submit', function (e) {
var spinner = $('#loader');
for ( instance in CKEDITOR.instances ) {
CKEDITOR.instances[instance].updateElement();
}
e.preventDefault();
spinner.show();
var serializedData = $(this).serialize();
$.ajax({
type: 'POST',
url: "post/ajax/board/",
data: serializedData,
success: function (data) {
if($('input[type="checkbox"]').prop("checked") == true){
//some codes
...
//take some serialised data and populate the table
// THIS IS WHERE THE ISSUE STARTS
var data = JSON.parse(data["data"]);
var fields = data[0]["fields"];
$("#boardsTable tbody").prepend(
`<tr>
<td>${fields["name"]||""}</td>
<td>${fields["url"]||""}</td>
<td>${fields["lead"]||""}</td>
</tr>`
);
// invoke datables draw() method to refresh the table
table.draw();
setTimeout(function(){
spinner.hide();
}, 1000);
console.log("Checkbox is checked. Modal will not be closed");
}
else if($('input[type="checkbox"]').prop("checked") == false){
// some codes
...
table.draw();
// more codes
}
},
error: function (jqXHR, textStatus, errorText) {
let data = jqXHR.responseJSON;
// more codes
console.log('There are some errors on the submitted form. Check the data errors array')
console.log(data)
}
})
});
//clear up the error logs when a user enters a value in the highlighted input field
});
I used the datatables reload API.
table = $("#boardsTable").DataTable().ajax.reload();
In your AJAX success function, you can draw it like so:
success: function(data) {
console.log(data);
if (data.d != null && data.d != undefined && data.d.results.length > 0) {
var table = $('#boardsTable').DataTable();
table.rows.add(data.d.results).draw();
}
}
I'm trying to build search filter with .keyup function. When i write one char in search textbox its works fine, but when i try to delete char, or add one more then it crushes and throws error "Internal server error". What im i doing wrong? I tried to parse given/taken data to json/html and it didn't help. Here is my script code:
<script>
$(document).ready(function () {
$("#Search").keyup(function () {
var searchby = $("#searchby").val();
var searchVal = $("#Search").val();
var setData = $("#dataSearching");
var catId = $("#categoryID").val();
setData.html("");
$.ajax({
async: true,
type: "get",
url: "/Default/GetSearchingData?categoryID=" + catId + "&searchBy=" + searchby + "&searchValue=" + searchVal,
dataType: "json",
contentType: "html",
success: function (result) {
if (result.length == 0) {
setData.append('<tr><td colspan="7" style="color: red;">Nie odnaleziono szukanej frazy</td></tr>');
} else {
for (var i in result) {
var Data = "<tr>" +
"<td>" + result[i].AlbumID + "</td>" +
"<td>" + result[i].AlbumName + "</td>" +
"<td>" + result[i].BandName + "</td>" +
"<td>" + result[i].AlbumCover + "</td>" +
"<td>" + result[i].Year + "</td>" +
"<td>" + parseFloat(result[i].Price) + "</td>" +
"<td>" +
"<button id=" + result[i].AlbumID + ' type="button" class="btn btn-primary myModals" data-toggle="modal" data-target="#exampleModal-' + result[i].AlbumID + '">' +
"Zobacz </button>" +
'<div class="modal fade" id="exampleModal-' + result[i].AlbumID + '" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel-' + result[i].AlbumID + '" aria-hidden="true">' +
'<div class="modal-dialog" role="document">' +
'<div class="modal-content">' +
'<div class="modal-header">' +
'<h5 class="modal-title" id="exampleModalLabel-' + result[i].AlbumID + '">' + result[i].AlbumName + ", " + result[i].Year + ", " + result[i].BandName + "</h5>" +
'<button type="button" class="close" data-dismiss="modal" aria-label="Close">' +
'<span aria-hidden="true">×</span> </button> </div>' +
'<div id="parent-' + result[i].AlbumID + '" class="modal-body">' +
"</div>" +
'<div class="modal-footer">' +
'<button id="closeModal" type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>' +
"</div>" +
"</div>" +
"</div>" +
"</div>" +
"</td>" +
"<td>"+
'<input id="categoryID" class="hidden" type="submit" value="' + result[i].CategoryID + "/>" +
"</td>"+
"</tr>";
setData.append(Data);
}
}
},
error: function (xhr, ajaxOptions, thrownError) {
//alert(xhr.responseText);
alert("Error!!: " + thrownError);
},
xhr: function () {
var xhr = new window.XMLHttpRequest();
return xhr;
}
});
});
});
</script>
And here is my action for searching in DefaultController:
public JsonResult GetSearchingData(int categoryID, string searchBy, string searchValue)
{
var albumsWithCategory = (from album in Album.GetAlbumList()
join category in Category.GetCategoriesList()
on album.CategoryID equals category.CategoryID
where (categoryID == album.CategoryID)
select album).ToList();
List<Album> newAlbumList;
if (searchBy == "AlbumName")
{
newAlbumList = albumsWithCategory.Where(x => x.AlbumName.StartsWith(searchValue, StringComparison.InvariantCultureIgnoreCase) || searchValue == null).ToList();
return Json(newAlbumList, JsonRequestBehavior.AllowGet);
}
else
{
newAlbumList = albumsWithCategory.Where(x => x.BandName.StartsWith(searchValue, StringComparison.InvariantCultureIgnoreCase) || searchValue == null).ToList();
return Json(newAlbumList, JsonRequestBehavior.AllowGet);
}
}
Here is my data model (if it would be useful to find issue):
public class BigViewModel
{
public IEnumerable<Album> Albums { get; set; }
public IEnumerable<Category> Categories { get; set; }
public IEnumerable<Order> Orders { get; set; }
public IEnumerable<Song> Songs { get; set; }
}
Image with error:
enter image description here
I believe that error is due formatting in query parameters. Instead of keyup i would try to use input event and instead of building query url i would use data property.
$("#Search").on("input", function () {
//...
$.ajax({
url: "/Default/GetSearchingData",
type: "get",
dataType: "json",
data: {
categoryID: Number(catId),
searchBy: searchBy,
searchValue: searchVal
},
success: function(result) {
if (result.length > 0)
{
var rows = response.map(item => {
return `
<tr>
<td>${item.AlbumID}</td>
<td>${item.AlbumName}</td>
<td>${item.BandName}</td>
<td>${item.AlbumCover}</td>
<td>...</td>
</tr>
`;
}).join("");
setData.html( `<table>${rows}</table>` );
} else {
setData.html( "<table><tr>Not found</tr></table>" );
}
},
error: function(xhr) { }
});
});
function GetPage(pageIndex) {
debugger;
$.ajax({
cache: false,
//url: "/EmailScheduler/",
url: '#(Url.RouteUrl("EmailScheduler"))',
type: "POST",
data: { "selectValue": pageIndex },
traditional: true,
dataType: "json",
success: function (data) {
debugger;
$('#GridRows').empty();
$('#pager').empty();
var trHTML = '';
var htmlPager = '';
$.each(data.Customers, function (i, item) {
trHTML += '<table class="table-bordered col-offset-12"><tr style="text-align:center">'
+'<td id="tblFirstName"> ' + item.FirstName + '</td>'
+'<td id="tblLastName"> ' + item.LastName + '</td>'
+'<td id="tblEmailID"> ' + item.EmailID + '</td>'
+'<td id="tblCustomerType"> ' + item.CustomerType + '</td>'
+'<td id="tblCustomerDesignation"> ' + item.CustomerDesignation + '</td>'
+' <td><div class="checkbox control-group"><label><input type="checkbox" id="item.CustomerID" value="item.CustomerID" onclick="AddRemoveCustomer(item.CustomerID)" class="checkBoxClass"/></label></div></td></tr></table>'
});
$('#GridRows').append(trHTML);
if (data.Pager.EndPage > 1) {
htmlPager += '<ul class="pagination">'
if (data.Pager.CurrentPage > 1) {
htmlPager += '<li><input class="myButton" style="width:25px;height:25px;" type="button" id="1" style="font-weight:bold;" value="<<" /></li><li><input type="button" class="myButton" id="' + (data.Pager.CurrentPage - 1) + '"value="<"></li>'
}
for (var page = data.Pager.StartPage; page <= data.Pager.EndPage; page++) {
htmlPager += '<li class="' + (page == data.Pager.CurrentPage ? "active" : "") + '"><input type="button" class="myButton" id="' + page + '" value="' + page + '"/></li>'
}
if (data.Pager.CurrentPage < data.Pager.TotalPages) {
htmlPager += '<li><input type="button" class="myButton" id="' + (data.Pager.CurrentPage + 1) + '" value=">"/></li><li><input type="button" class="myButton" id="' + (data.Pager.TotalPages) + '" value=">>"/></li>'
}
htmlPager += '</ul>'
}
$('#pager').append(htmlPager);
},
error: function (jqXHR, textStatus, errorThrown) {
debugger;
}
});
}
**
Scenario:-
**
In this ajax table rows generated.
How to call onClick function for checkbox in Ajax generated rows?
I want to call onClick function in which checked id's stored in hidden
field.
what should i do?
try to update :
+' <td><div class="checkbox control-group"><label><input
type="checkbox" id="'+item.CustomerID+'"
value="'+item.CustomerID+'" class="checkBoxClass"/>
</label></div></td></tr></table>'
and add this :
$(document).on('click', '#GridRows .checkBoxClass' ,
function(){
alert('hello');//todo something....
});
Try to do something like this
function delegateAction(){
$('.checkBoxClass').click(function(event){
// do some action
});
}
delegateAction();
After ajax load you can call "delegateAction()", and the event click will be activated.
I have nested callabcks but resulted output is not ordered correctly. My ajax results are in ascending orders of id but html generated is random. can someone help me out pls?
var formatedhtml = '';
$.ajax({
type: "POST",
url: BASE_URL + 'index.php/orders/read',
dataType: 'json',
success: function(data) {
$.each(data, function(key, value) {
console.log(value);
getdetails(value['id'], function(output) {
formatedhtml = formatedhtml +
'<div class="col-md-4 col-sm-4 col-lg-3 col-xs-6">' +
' <div class="row">' +
' <div class="orderno">' + value['id'] + '</div>' +
'<div class="tableno">' + value['tableno'] + '</div>' +
'<div class="ordertype">' + value['type'] + '</div>' +
'<div class="timestamp">' + value['created'] + '</div>' +
' </div>' +
'<hr>';
$.each(JSON.parse(output['items']), function(k, val) {
formatedhtml = formatedhtml + '<div class="row">' +
'<div class="quantity">' + val[3] + '</div>' +
'<div class="item">' + '</div>' +
'</div>';
});
formatedhtml = formatedhtml +
'<div class="row">' +
'<div class="notes">' + value['id'] + '</div>' +
'</div>' +
'</div>';
$("#orderlist").html(formatedhtml);
console.log(output);
});
});
}
});
edit:
Here is getdetails function. its an ajax request.
function getdetails(id, callback) {
var result;
$.ajax({
type: "POST",
url: BASE_URL + 'index.php/orders/readdetails',
dataType: 'json',
data: {
id: id,
},
success: function(data) {
callback(data[0]);
}
});
};
There are a lot of ways to achieve this, one is to use a promise and sort by id when all requests are done. Another you could create the template and append the details on callback as each detail request has an id you can define in your template a class like 'id-'+value['id'] and use jquery selector and append detail template.
Another solution would be to create a function loop that calls itself untill orderCount == orderLoaded.
Job is done synchronously (takes more time)
//Mock ajax function
$.ajax = function (param) {
if(param.url.indexOf('readdetails') != -1){
param.success(itemsData);
} else {
param.success(ordersData);
}
};
//Mock data
var ordersData = [
{ id : 1, tableno : 'xyz', type: 'invoice', created: '01/01/2001' },
{ id : 2, tableno : 'xyz', type: 'invoice', created: '01/01/2001' },
{ id : 3, tableno : 'xyz', type: 'invoice', created: '01/01/2001' }
];
var itemsData = [
{ id : 1, orderid: 1, quantity: 5 },
{ id : 2, orderid: 1, quantity: 2 },
{ id : 3, orderid: 1, quantity: 1 }
];
// Globals
var formatedhtml = [];
var orders = [];
var lastOrderLoaded = 0;
var BASE_URL = 'localhost/';
function tpl(order, items) {
var html = '<tr class="col-md-4 col-sm-4 col-lg-3 col-xs-6">' +
' <td class="orderno">' + order['id'] + '</td>' +
'<td class="tableno">' + order['tableno'] + '</td>' +
'<td class="ordertype">' + order['type'] + '</td>' +
'<td class="timestamp">' + order['created'] + '</td>' +
' </tr>';
$.each(items, function(key, item) {
html += '<tr class="row">' +
'<td class="item">item: ' + item.id + '</td>' +
'<td class="quantity">quantity: ' + item.quantity + '</td>' +
'</tr>';
});
html +=
'<tr class="row">' +
'<td class="notes"> notes </td>' +
'<td class="notes"> order id ' + order['id'] + '</td>' +
'</tr>' +
'</tr>';
formatedhtml.push({ id: order.id, html : html });
}
$.ajax({
type: "POST",
url: BASE_URL + 'index.php/orders/read',
dataType: 'json',
success: function(data) {
lastOrderLoaded = 0;
orders = data;
getdetails(orders[0]);
}
});
function getdetails(order) {
$.ajax({
type: "POST",
url: BASE_URL + 'index.php/orders/readdetails',
dataType: 'json',
data: {
id: order.id,
},
success: function(data) {
tpl(order, data);
if(lastOrderLoaded < orders.length - 1){
lastOrderLoaded++;
getdetails(orders[lastOrderLoaded]);
} else {
formatedhtml.forEach(function(element){
$("#orderlist").append(element.html);
}); // end each
}
}
});
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="orderlist" border="1">
<tr><th>id</th><th>no</th><th>type</th><th>date</th></tr>
</table>
Promise Solution:
Job is done asynchronously (might take less time also bombards the server with many requests at once)
var formatedhtml = [];
function tpl(order, items) {
var html = '<div class="col-md-4 col-sm-4 col-lg-3 col-xs-6">' +
' <div class="row">' +
' <div class="orderno">' + order['id'] + '</div>' +
'<div class="tableno">' + order['tableno'] + '</div>' +
'<div class="ordertype">' + order['type'] + '</div>' +
'<div class="timestamp">' + order['created'] + '</div>' +
' </div>' +
'<hr>';
$.each(JSON.parse(items['items']), function(key, item) {
var html += '<div class="row">' +
'<div class="quantity">' + item[3] + '</div>' +
'<div class="item">' + '</div>' +
'</div>';
});
html +=
'<div class="row">' +
'<div class="notes">' + order['id'] + '</div>' +
'</div>' +
'</div>';
formatedhtml.push({ id: order.id, html : html });
}
$.ajax({
type: "POST",
url: BASE_URL + 'index.php/orders/read',
dataType: 'json',
success: function(data) {
var syncLoad = [];
$.each(data, function(key, value) {
syncLoad.push(getdetails(value, tpl));
});
$.when.apply($, syncLoad).done(function() {
formatedhtml.sort(function(a, b){
return a.id - b.id;
});
formatedhtml.forEach(function(element){
$("#orderlist").append(element.html);
});
});
}
});
function getdetails(order, callback) {
return $.ajax({
type: "POST",
url: BASE_URL + 'index.php/orders/readdetails',
dataType: 'json',
data: {
id: order.id,
},
success: function(data) {
callback(order, data[0]);
}
});
};
Use async:false in your getDetails() ajax call.
function getdetails(id, callback) {
var result;
$.ajax({
type: "POST",
url: BASE_URL + 'index.php/orders/readdetails',
dataType: 'json',
async: false,
data: {
id: id,
},
success: function (data) {
callback(data[0]);
}
});