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.
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
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);
}
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++) {
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.