Creating html table using javascript ajax calls in sequential order? - javascript

I am new to JavaScript. I am creating one table dynamically; I am facing a problem with the order of execution. I know JavaScript code won't execute sequentially, but what will be the work around?
First I will brief what I am trying to do.
1) loadList () -> I will call this method on click of load data button
here I will fire AJAX request to get data
2) using the result of above AJAX request, I am trying to create table rows
3) few table rows td having combo box, whose value to be filled using another AJAX call, passing the rowObject value
Below is my code:
var loadList = function(){
//ajax call
$.ajax({
url:"tworows.json",
type: "GET",
dataType : "json"
})
.done(function(data, textStatus, jqXHR){
generateTable(data);
});
};
function generateTable(data){
$("#gridTable").empty();
//create table header
var headertr = $("<tr><th>col1 </th><th>col 2</th><th>col 3</th><th>col 4</th><th>col 5</th><th>col 6</th><th>col 7</th></tr>");
//get table id from jquery
var tableelement = $("#gridTable");
//add header row to table
tableelement.append(headertr);
for(var i=0; i< data.links.id.length; i++){
tableelement.append(createRow(data.links.id[i]));
}
}
function createRow(rowObject){
//used to create combo box 1 based row 1 value
var combo1 = createCombo1(rowObject);
//used to create combo box 2 based row 1 value
var combo2 = createCombo2(rowObject);
var trElement = "<tr>"+
"<td><input type='text' name='col1name' value='"+rowObject.Number+"' onblur='handleInput(this)'/></td>"+
"<td><input type='text' name='col3name' value='"+rowObject.name+"'/></td>"+
"<td><input type='text' name='col3name' value='"+rowObject.quantity+"'/></td>"+
"<td>"+combo1+"</td>"+
"<td>"+combo2+"</td>"+
"<td><button>Del</button></td>" +
"<td><button>Add</button></td></tr>";
return trElement;
}
function createCombo1(rowObject){
var comboList = [];
//call ajax to get combo value
$.ajax({
url:"combo1data.json",
type: "GET",
dataType : "json",
async : false
})
.done(function(data, textStatus, jqXHR){
comboList = data.links.id;
});
var cmb1 = "<select name='cmb1' onchange='handlecmb1Change(this)'>";
for(var i=0;i < comboList.length; i++){
cmb1 +="<option value='"+comboList[i].id+"'>"+comboList[i].name+"</option>";
}
cmb1 += "</select>";
return cmb1;
}
function createCombo2(rowObject){
var comboList = [];
//call ajax to get combo value
$.ajax({
url:"combo2data.json",
type: "GET",
dataType : "json",
async : false
})
.done(function(data, textStatus, jqXHR){
comboList = data.links.id;
});
var cmb2 = "<select onchange='handlecmb2Change(this)'>";
for(var i=0;i < comboList.length; i++){
cmb2 +="<option value='"+comboList[i].id+"'>"+comboList[i].name+" </option>";
}
cmb2 += "</select>";
return cmb2;
}
Here row is creating first, after that control is going to createCombo methods. Because of this I am not getting combo boxes in td.
I want to create combobox based on first result of AJAX call; using the first result I need to call other 2 AJAX calls and populate them in the td combobox.

Please use below code block, this might be solve your problem. Your requirement need synchronous execution of methods, for this you need to use callback structure.
below is the code :
var loadList = function(){
//ajax call
$.ajax({
url:"tworows.json",
type: "GET",
dataType : "json"
})
.done(function(data, textStatus, jqXHR){
generateTable(data);
});
};
function generateTable(data){
$("#gridTable").empty();
//create table header
var headertr = $("<tr><th>col1 </th><th>col 2</th><th>col 3</th><th>col 4</th><th>col 5</th><th>col 6</th><th>col 7</th></tr>");
//get table id from jquery
var tableelement = $("#gridTable");
//add header row to table
tableelement.append(headertr);
for(var i=0; i< data.links.id.length; i++){
tableelement.append(createRow(data.links.id[i]));
}
}
function createRow(rowObject){
var trElement = "<tr>";
//used to create combo box 1 based row 1 value
var combo1 = createCombo1(rowObject,function(response){
//used to create combo box 2 based row 1 value
var combo2 = createCombo2(rowObject,function(result){
trElement+= "<td><input type='text' name='col1name' value='"+rowObject.Number+"' onblur='handleInput(this)'/></td>";
trElement+="<td><input type='text' name='col3name' value='"+rowObject.name+"'/></td>";
trElement+="<td><input type='text' name='col3name' value='"+rowObject.quantity+"'/></td>";
trElement+="<td>"+response+"</td>";
trElement+="<td>"+result+"</td>";
trElement+="<td><button>Del</button></td>";
trElement+="<td><button>Add</button></td></tr>";
});
});
return trElement;
}
function createCombo1(rowObject,callback){
var comboList = [];
//call ajax to get combo value
$.ajax({
url:"combo1data.json",
type: "GET",
dataType : "json"
})
.done(function(data, textStatus, jqXHR){
comboList = data.links.id;
var cmb1 = "<select name='cmb1' onchange='handlecmb1Change(this)'>";
for(var i=0;i < comboList.length; i++){
cmb1 +="<option value='"+comboList.id+"'>"+comboList.val+"</option>";
}
cmb1 += "</select>";
return callback(cmb1);
});
}
function createCombo2(rowObject,callback){
var comboList = [];
//call ajax to get combo value
$.ajax({
url:"combo2data.json",
type: "GET",
dataType : "json"
})
.done(function(data, textStatus, jqXHR){
comboList = data.links.id;
var cmb2 = "<select name='cmb1' onchange='handlecmb1Change(this)'>";
for(var i=0;i < comboList.length; i++){
cmb1 +="<option value='"+comboList.id+"'>"+comboList.val+"</option>";
}
cmb2 += "</select>";
return callback(cmb2);
});
}
thanks

There are several problems that need to be addressed.
First, the return value from an ajax callback won't go anywhere.
This line
var combo1 = createCombo1(rowObject);
Will set combo1 to undefined every single time. Because createCombo1() doesn't return anything. The anonymous function inside of createCombo1() is what returns the value your looking for, but in this case you can't use that return value.
What I recommend for createCombo1() and createCombo2() is to save the return value to a global variable or maybe even an array, so you can access them when they are done.
Which brings me to the next problem...how do you know when they are done?
jQuery has something called a deferred object. Which allows you to chain multiple callbacks to one function. There is a similar SO question that addresses how to use this using When().
Here is the question
There is still a lot to do on your end, but hopefully this will point you in the right direction.

Related

Looping inside .append jquery

I've 2 array of elements coming from PHP. I've stored the elements in 2 variable in javascript
then looped 1 variable to create a table to show the element
I want to create element in append and loop another array to bind or dynamically show other elements in
here is my code
<script>
$(document).ready(function(){
$("#courier_id").change(function (){
var c_id = $(this).val();
var totalCOD = 0;
$('#data').empty();
$.ajax({
type: "POST",
dataType: "json",
data: {
'delivery_courier' : c_id
},
url: "<?=base_url()?>Admin/get_deliverd_consignmnet",
success: function(data) {
var status = data.status;
var consignment = data.consignment;
if(consignment.length > 0){
$("#table").css({"display":"block"});
$("#nodata").css({"display":"none"});
$.each(consignment, function(idx, obj) {
$("#data").append("<tr><td><input value="+obj.c_id+" total="+obj.cod+" type=checkbox style='width: 24px;height: 23px;'/>"+"</td><td>"+obj.c_id+"</td><td>"+obj.consignee_name+"</td><td>"+obj.consignee_address+"</td><td>"+obj.cod+"</td><td>"+obj.code+" - "+obj.description+"</td><td><select>'2nd loop start here'<option></option>'2nd loop end here'</select></td></tr>");
});
$("#data").append("<tr><td colspan='4'><b><center>Total</center></b></td><td id='field_results'></td><td></td><td></td></tr>");
$("input:checkbox").click(function() {
var output=0;
$("input:checked").each(function() {
output += Number($(this).attr('total'));
});
$("#field_results").html(output);
});
}
else{
$("#table").css({"display":"none"});
$("#nodata").css({"display":"block"});
}
}
});
});
});
1st var looped is consignment
2nd var that i want to loop is status
Create the loop for the options first and them save them in a string variable:
var options = "";
$.each(status, function () {
options += "<option>"+status.attribute+"</option>"
})
Then, concat this string to your append:
$("#data").append("<tr><td><input value="+obj.c_id+" total="+obj.cod+" type=checkbox style='width: 24px;height: 23px;'/>"+"</td><td>"+obj.c_id+"</td><td>"+obj.consignee_name+"</td><td>"+obj.consignee_address+"</td><td>"+obj.cod+"</td><td>"+obj.code+" - "+obj.description+"</td><td><select>"+options+"</select></td></tr>");
There's lots of ways to do it, but I think this one is simplier for you because it is aligned with your line of thought.

How to get JSON data into option list

I am getting JSON in the following format (as array of objects)
[{"0":"Ahmednagar","city_name":"Ahmednagar","1":"1","city_id":"1"},{"0":"Akola","city_name":"Akola","1":"2","city_id":"2"},{"0":"Amravati","city_name":"Amravati","1":"3","city_id":"3"},{"0":"Aurangabad","city_name":"Aurangabad","1":"4","city_id":"4"},{"0":"Beed","city_name":"Beed","1":"5","city_id":"5"},{"0":"Bhandara","city_name":"Bhandara","1":"6","city_id":"6"},{"0":"Buldhana","city_name":"Buldhana","1":"7","city_id":"7"},{"0":"Chandrapur","city_name":"Chandrapur","1":"8","city_id":"8"},{"0":"Dhule","city_name":"Dhule","1":"9","city_id":"9"},{"0":"Gadchiroli","city_name":"Gadchiroli","1":"10","city_id":"10"},{"0":"Gondia","city_name":"Gondia","1":"11","city_id":"11"},{"0":"Hingoli","city_name":"Hingoli","1":"12","city_id":"12"},{"0":"Jalgaon","city_name":"Jalgaon","1":"13","city_id":"13"},{"0":"Jalna","city_name":"Jalna","1":"14","city_id":"14"},{"0":"Kolhapur","city_name":"Kolhapur","1":"15","city_id":"15"},{"0":"Latur","city_name":"Latur","1":"16","city_id":"16"},{"0":"Mumbai City","city_name":"Mumbai City","1":"17","city_id":"17"},{"0":"Mumbai Suburban","city_name":"Mumbai Suburban","1":"18","city_id":"18"},{"0":"Nagpur","city_name":"Nagpur","1":"19","city_id":"19"},{"0":"Nanded","city_name":"Nanded","1":"20","city_id":"20"},{"0":"Nandurbar","city_name":"Nandurbar","1":"21","city_id":"21"},{"0":"Nashik","city_name":"Nashik","1":"22","city_id":"22"},{"0":"Osmanabad","city_name":"Osmanabad","1":"23","city_id":"23"},{"0":"Palghar","city_name":"Palghar","1":"36","city_id":"36"},{"0":"Parbhani","city_name":"Parbhani","1":"24","city_id":"24"},{"0":"Pune & Pimpri-Chinchwad ","city_name":"Pune & Pimpri-Chinchwad ","1":"25","city_id":"25"},{"0":"Raigad","city_name":"Raigad","1":"26","city_id":"26"},{"0":"Ratnagiri","city_name":"Ratnagiri","1":"27","city_id":"27"},{"0":"Sangli","city_name":"Sangli","1":"28","city_id":"28"},{"0":"Satara","city_name":"Satara","1":"29","city_id":"29"},{"0":"Sindhudurg","city_name":"Sindhudurg","1":"30","city_id":"30"},{"0":"Solapur","city_name":"Solapur","1":"31","city_id":"31"},{"0":"Thane","city_name":"Thane","1":"32","city_id":"32"},{"0":"Wardha","city_name":"Wardha","1":"33","city_id":"33"},{"0":"Washim","city_name":"Washim","1":"34","city_id":"34"},{"0":"Yavatmal\t","city_name":"Yavatmal\t","1":"35","city_id":"35"}]
ajax call to get json
$(document).ready(function(){
$("#select_state").change(function() {
var $state_var=$('#select_state').val();
alert("Selected State Value "+$state_var);
//make the ajax call
$.ajax({
url: 'ajax/location.php',
type:'GET',
data: {
state_name : $state_var
},
success: function(city_list) {
console.log(city_list);
var options = '';
for (var i = 0; i < city_list.length; i++) {
var city = city_list[i];
options += '<option value="' + city.city_id + '">' + city.city_name + '</option>';
}
$('#select_city').html(options);
$('#select_city').show();
}
});
});
});
Now it gives me only undefined is option list
You need to add:-
dataType;'json',
In your $.ajax code so that your response is automatically parsed and success function will execute properly.
Like below:-
$.ajax({
url: 'ajax/location.php',
type:'GET',
dataType:'json', // add this
data: {
state_name : $state_var
},.....rest code

How to append the values in table using AJAX

Here i am passing javascript varaible into PHP function using AJAX ,here it will be working fine,** console.log(fname);** Here i got all values but append the tables means i am getting [object Object],how can solve this error
<script type="text/javascript">
$(document).ready(function(){
$("#reservation").on("change", function() {
var reservation = $(this).val();
$.ajax({
type: 'post',
url: 'date-range.php',
data: {
logindate: reservation,
},
success: function( data ) {
var res=jQuery.parseJSON(data);// convert the json
console.log(res);
if(res['status']=="success"){
var htmlString='';
$.each( res['data'], function( key, value ) {
htmlString+='<tr>';
var ssm_id = value.ssm_id; // here i got ssmid
htmlString+='<td>'+value.ssm_id+'</td>';
htmlString+='<td>'+ $.ajax({
type: 'post',
url: 'config/functions.php',
data: {
ssm_id: ssm_id,
},
success: function( fname ) {
console.log(fname);//HERE I GOT ALL VALUES
htmlString+='<td>'+fname+'</td>';// BUT HERE I CAN'T APPENT THE VALUES IN TABLE
}
});+'</td>';
htmlString+='<td>'+'Muthuraja'+'</td>';
htmlString+='<td>'+'20-05-2016'+'</td>';
htmlString+='<td>'+'status'+'</td>';
htmlString+='<td>'+value.source+'</td>';
htmlString+='<td>'+ "<span style='color:green'>View Profile</span>"+'</td>';
/* htmlString+='<td>'+ "<span style='color:green'>Completed</span>"+'</td>';*/
htmlString+='</tr>';
});
$('#datatable-editable > tbody').empty().append(htmlString);
}
else{
$('#datatable-editable > tbody').empty().append("<center style='height:100px;padding-top:36px;color:red;font-size:17px;'><b>No matching records found</b></center>");
}
}
});
});
});
</script>
functions.php
<?php
$ssm_id = $_POST['ssm_id'];
if(!empty($ssm_id)){
echo firstname($ssm_id);
}
function firstname($id)
{
$f="SELECT firstname FROM register WHERE matri_id='$id'";
$rr=mysql_query($f);
while($row=mysql_fetch_array($rr)) {
$firstname = $row['firstname'];
}
return $firstname;
}
?>
Without knowing the exact format of your JSON, it's hard to give a definitive answer. However, assuming you have a JSON array of objects that represent your rows, you'd need to iterate over that array and for each object do the following:
Create a new <tr> element - var $tr = $('<tr/>');
For each item of information (I assume one item per <td>), create a <td> element and set its content - var $td = $('<td/>').html(x.y) (x is your current object, y is a field in the object) then append it to the row - $tr.append($td);.
Append the row before the last row in the existing table - $('.list-order tr:last').before($tr);
Following from the additional information provided in the question, the following code should do what you need to do:
success: function(result) {
//result is json format
var $tr = $('<tr/>');
$tr.append($('<td/>').html(result.itemname));
$tr.append($('<td/>').html(result.qty));
$tr.append($('<td/>').html(result.prices));
$('.list-order tr:last').before($tr);
}

how to count total number of ajax response data sets inside for loop?

i am calling an ajax and output api response in textbox. I want count total number of data sets received(counteri) and display it each time i click a button. For example if i click the button first time i want to an alert display counteri=20 and next time i click button it display counteri=40 and... counteri=60.
Currently my code keeps showing 20 each time and not adding the values. could any one tell me how to fix this.Thanks
<script>
var maxnumId = null;
var counteri= null;
function callApi() {
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "https://api.somesite.com/......"),
success: function(data) {
maxnumId = data.pagination.next_num_id;
for (var i = 0; i < 100; i++) {
$(".galaxy").append("<div class='galaxy-placeholder'><a target='_blank' href='" + data.data[i].link +"'><img class='galaxy-image' src='" + ok.images.standard_resolution.url +"' /></a></div>");
document.myform.outputtext.value = document.myform.outputtext.value+data.data[i].images.ok.url+'\n' ;
//alert('www!'+i);
counteri=i;
}
}
});
counteri=counteri+counteri;
alert('counteri is now: ' + counteri);
}
</script>
<body>
<br>
<center>
<div id="myDiv"></div>
<div class="galaxy"></div>
<button id="mango" onclick="callApi()">Load More</button>
</html>
EDIT:
Adding this in start of success added up total number of records from ajax response
var num_records = Object.keys(data.data).length;
num_records2=num_records2+num_records;
alert('number of records:'+ num_records2);
and
var num_records2 =null; // outside function
Ajax are async calls.
Move the alert to just after the for. Not outside the success callback.
Looks like the problem is that you are setting counteri to the value of i instead of adding the value of i. Try this instead:
counteri += i;
Ajax calls are asynchronous. You should increment your counter on success, not outside of the ajax call. Something like this:
function callApi() {
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "https://api.somesite.com/......",
success: function(data) {
maxnumId = data.pagination.next_num_id;
for (var i = 0; i < 100; i++) {
document.myform.outputtext.value = document.myform.outputtext.value+data.data[i].images.ok.url+'\n' ;
}
counteri=counteri+i;
alert('counteri is now: ' + counteri);
}
});
}
Considering that your ajax request is executed with success, to get what you want you need to declare the i variable before for ( ....) loop as is the follow script:
var counteri = 0;
function callApi() {
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "https://api.somesite.com/......",
success: function(data) {
var i,
maxnumId = data.pagination.next_num_id;
for (i = 0; i < 100; i++) {
document.myform.outputtext.value = document.myform.outputtext.value+data.data[i].images.ok.url+'\n' ;
}
counteri=counteri+i;
alert('counteri is now: ' + counteri);
}
});
}
Please ses here demo
EDIT
Also i have rechecked if the variable i is not declared before for(...) loop and works OK. So, the only fix is to remove counter=i from for(...) loop and to change the counteri=counteri+counteri; to counteri+=i;
Take in consideration that the ajax requests produce a number of different events that you can subscribe to. Depending of your needs you can combine this events to accomplish the desired behavior. The complete list of ajax events is explained here
EDIT2
After reading your comments, i see that you need the last value of i globally,
you need to add a second global variable too keep the sum of last i during all ajax requests.
To do this, id have added a minor change to answer:
var counteri = 0,
totali =0;
function callApi() {
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "https://api.somesite.com/......",
success: function(data) {
var i,
maxnumId = data.pagination.next_num_id;
for (i = 0; i < 100; i++) {
document.myform.outputtext.value = document.myform.outputtext.value+data.data[i].images.ok.url+'\n' ;
}
counteri = i;
totali = totali + i;
alert('totali is now: ' + totali );
}
});
}
JSFiddle demo
EDIT 3
After your last comment, you need to add in the API response the number of returned rows. For this, you need to change for (i = 0; i < 100; i++) { to something like this:
var num_records = data.num_rows;
for (i = 0; i < num_records ; i++) {
or, without adding the number of rows in response
var num_records = Object.keys(data.data).length;
for (i = 0; i < num_records ; i++) {

Filtering Selection from AJAX Call

What I want to do is, I want to display the selection that registered under accType=Acc1 in Selection. The AccInfo function is my ajax call. I would like to pass the parameter in data. The Acc_response function is a function to operate the option value. I would like to show the branchCode,accType,Code, that is registered under Acc1. How can I do that?
function AccInfo(Acc1){
$.ajax({
type:"POST",
datatype:"json",
async:true,
data:{A:Acc1},
url:AccInfo_url,
success: function(data){
Acc_response(data);
},
error: function(jqXHR, textStatus){
errorHandling(textStatus);
}
})
}
function Acc_response(data){
console.log(data);
for (var i=0;i<data.ClientInfo.length;i++)
{
var $option=$('<option />');
$option.attr('value', data.ClientInfo[i].branchCode+"|"+data.ClientInfo[i].Code+"|"+data.ClientInfo[i].accType);
$option.text(data.ClientInfo[i].accType+" (" + data.ClientInfo[i].Code+"-"+data.ClientInfo[i].branchCode+") ";
$('#Selection').append($option);
}
}
This is more usefull;
var selectedAccType = 'your account type';
//you can set this at post action to
function Acc_response(data){
data.ClientInfo.forEach(function(client) {
if(client.accType==selectedAccType){
var optionValue = client.branchCode+'|'+client.Code+'|'+client.accType;
var optionText = client.accType+'('client.Code+'-'+client.branchCode+')';
var option = '<option value="'+optionValue+'">'+optionText+'</option>';
$('#Selection').append(option);
}
});
}
This works for if you have one <select>. If you have more selects send us your html code.

Categories