How to append the values in table using AJAX - javascript
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);
}
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.
PHP iterate through cookies arrays
In my cakephp application I am trying to create a commenting functionality. So I use an ajax request to get the comments and then clone an html template and append it to the page: //load comments $(document).ready(function(){ $.ajax({ type: 'POST', url: '/app/tasks/getComments', datatype: 'json', beforeSend: function (xhr) { // Add this line xhr.setRequestHeader('X-CSRF-Token', $('[name="_csrfToken"]').val()); }, data: { task_id : "<?php echo $task->id; ?>" }, success: function( data ) { for (var i=0; i < data.length; i++) { //Clone the template var item = $(template).clone(); document.cookie = 'photos['+i+']='+data[i].user.photo; document.cookie = 'names['+i+']='+data[i].user.username; //Find the element $(item).find('#comment_photo').html('<?php if(isset($_COOKIE["photos[$num]"])) {echo $this->Html->image($_COOKIE["photos[$num]"], ["class" => "avatar avatar-online", "alt" => $currentUser->username]); } ?>'); $(item).find('#comment_username').html('<?php if(isset($_COOKIE["names[$num]"])) { echo $_COOKIE["names[$num]"]; }?>'); $(item).find('#comment_time').html(moment(data[i].created_date, 'DD-MM-YYYY hh:mm:ss').format('MMMM Do YYYY, h:mm:ss a')); $(item).find('#comment_text').html(data[i].comment); $(item).find('#comment_id').html(data[i].id); //Append to the source $('#target').append(item); } } }); }); In order to access the returned results in php I store them in cookie arrays (photos[], names[]). How I can set and update the value of $num in order to iterate the arrays in every html code append? Is it possible to achieve what I want with this approach? Or I need a complete new one?
The solution was much simpler than I actually thought... I did it with JQuery like this: ....... $(item).find('#comment_photo').prepend("<img src='/app/img/' class='avatar avatar-online'/>"); $(item).find('.avatar.avatar-online').prop('src', '/app/img/'+data[i].user.photo); ......
How to find all the children for its parent in Jquery?
I'm using Codeigniter and Jquery with AJAX method to query data from two tables in my database with select join from table group with table cat. This is table description Table1: cat ======c_id======fk_group_id====cat_name=== ======1========1==============cat1======= ======2========1==============cat2======= ======3========1==============cat3======= ======4========1==============cat4======= Table2: cat_group. ======gid=======gname====gstat============ ======1========1=========1============== ======2========1=========1============== ======3========1=========1============== ======4========1=========1============== Here is my Model: This function will selct from table cat_group join with table Cat on gid = cat.fk_group_id. public function cat(){ $this->db->select('cat_group.*, cat.*'); $this->db->from('cat_group'); $this->db->join('cat', 'cat.fk_group_id = cat_group.gid','all')->where('cat_group.gstatus = 1'); return $this->db->get()->result(); } My function in Controller: I call method cat from Model and echo data as Json_encode to the client browsers public function select_cat_by_group(){ $this->load->model("main/slide_cat_m"); $val = $this->slide_cat_m->cat(); if(!$val){ return false; }else{ echo json_encode($val); } } Jquery Ajax $.ajax({ method: "GET", url: '<?PHP echo base_url('main/select_cat_by_group');?>', dataType: "Json", success: function (data) { $.each(data, function (i, val) { if(val.fk_group_id = gid){ //I want to select all the rows in table cat where fk_groupd_id = gid of table cat_group but I can't } }); } }) My Json [{"gid":"1","gtype":"1","g_name":"a","gstatus":"1","gad_stat":"1","gsrc":"asset\/img\/cat\/","gimg":"cat_ads.jpg","c_id":"1","fk_group_id":"1","cat_name":"fuck1","c_status":"1","type_for_group":"1","img":"9.jpg","src":"asset\/img\/main"},{"gid":"5","gtype":"2","g_name":"a","gstatus":"1","gad_stat":"0","gsrc":"asset\/img\/cat\/","gimg":"cat_ads.jpg","c_id":"5","fk_group_id":"5","cat_name":"cat_name","c_status":"1","type_for_group":"2","img":"9.jpg","src":"asset\/img\/main"},{"gid":"5","gtype":"2","g_name":"a","gstatus":"1","gad_stat":"0","gsrc":"asset\/img\/cat\/","gimg":"cat_ads.jpg","c_id":"6","fk_group_id":"5","cat_name":"cat_name","c_status":"1","type_for_group":"1","img":"9.jpg","src":"asset\/img\/main"},{"gid":"5","gtype":"2","g_name":"a","gstatus":"1","gad_stat":"0","gsrc":"asset\/img\/cat\/","gimg":"cat_ads.jpg","c_id":"7","fk_group_id":"5","cat_name":"cat_name","c_status":"1","type_for_group":"1","img":"9.jpg","src":"asset\/img\/main"},{"gid":"5","gtype":"2","g_name":"a","gstatus":"1","gad_stat":"0","gsrc":"asset\/img\/cat\/","gimg":"cat_ads.jpg","c_id":"8","fk_group_id":"5","cat_name":"cat_name","c_status":"1","type_for_group":"1","img":"9.jpg","src":"asset\/img\/main"},{"gid":"6","gtype":"1","g_name":"a","gstatus":"1","gad_stat":"1","gsrc":"asset\/img\/cat\/","gimg":"cat_ads.jpg","c_id":"9","fk_group_id":"6","cat_name":"cat_name","c_status":"1","type_for_group":"1","img":"9.jpg","src":"asset\/img\/main"},{"gid":"6","gtype":"1","g_name":"a","gstatus":"1","gad_stat":"1","gsrc":"asset\/img\/cat\/","gimg":"cat_ads.jpg","c_id":"10","fk_group_id":"6","cat_name":"cat_name","c_status":"1","type_for_group":"1","img":"9.jpg","src":"asset\/img\/main"},{"gid":"6","gtype":"1","g_name":"a","gstatus":"1","gad_stat":"1","gsrc":"asset\/img\/cat\/","gimg":"cat_ads.jpg","c_id":"15","fk_group_id":"6","cat_name":"cat_name","c_status":"1","type_for_group":"1","img":"9.jpg","src":"asset\/img\/main"},{"gid":"6","gtype":"1","g_name":"a","gstatus":"1","gad_stat":"1","gsrc":"asset\/img\/cat\/","gimg":"cat_ads.jpg","c_id":"16","fk_group_id":"6","cat_name":"cat_name","c_status":"1","type_for_group":"1","img":"9.jpg","src":"asset\/img\/main"},{"gid":"6","gtype":"1","g_name":"a","gstatus":"1","gad_stat":"1","gsrc":"asset\/img\/cat\/","gimg":"cat_ads.jpg","c_id":"17","fk_group_id":"6","cat_name":"cat_name","c_status":"1","type_for_group":"1","img":"9.jpg","src":"asset\/img\/main"},{"gid":"6","gtype":"1","g_name":"a","gstatus":"1","gad_stat":"1","gsrc":"asset\/img\/cat\/","gimg":"cat_ads.jpg","c_id":"18","fk_group_id":"6","cat_name":"cat_name","c_status":"1","type_for_group":"1","img":"9.jpg","src":"asset\/img\/main"},{"gid":"6","gtype":"1","g_name":"a","gstatus":"1","gad_stat":"1","gsrc":"asset\/img\/cat\/","gimg":"cat_ads.jpg","c_id":"19","fk_group_id":"6","cat_name":"cat_name","c_status":"1","type_for_group":"1","img":"9.jpg","src":"asset\/img\/main"},{"gid":"7","gtype":"1","g_name":"a","gstatus":"1","gad_stat":"0","gsrc":"asset\/img\/cat\/","gimg":"cat_ads.jpg","c_id":"20","fk_group_id":"7","cat_name":"cat_name","c_status":"1","type_for_group":"1","img":"9.jpg","src":"asset\/img\/main"},{"gid":"7","gtype":"1","g_name":"a","gstatus":"1","gad_stat":"0","gsrc":"asset\/img\/cat\/","gimg":"cat_ads.jpg","c_id":"21","fk_group_id":"7","cat_name":"cat_name","c_status":"1","type_for_group":"1","img":"9.jpg","src":"asset\/img\/main"},{"gid":"7","gtype":"1","g_name":"a","gstatus":"1","gad_stat":"0","gsrc":"asset\/img\/cat\/","gimg":"cat_ads.jpg","c_id":"22","fk_group_id":"7","cat_name":"cat_name","c_status":"1","type_for_group":"1","img":"9.jpg","src":"asset\/img\/main"},{"gid":"7","gtype":"1","g_name":"a","gstatus":"1","gad_stat":"0","gsrc":"asset\/img\/cat\/","gimg":"cat_ads.jpg","c_id":"23","fk_group_id":"7","cat_name":"cat_name","c_status":"1","type_for_group":"1","img":"9.jpg","src":"asset\/img\/main"},{"gid":"7","gtype":"1","g_name":"a","gstatus":"1","gad_stat":"0","gsrc":"asset\/img\/cat\/","gimg":"cat_ads.jpg","c_id":"24","fk_group_id":"7","cat_name":"cat_name","c_status":"1","type_for_group":"1","img":"9.jpg","src":"asset\/img\/main"},{"gid":"7","gtype":"1","g_name":"a","gstatus":"1","gad_stat":"0","gsrc":"asset\/img\/cat\/","gimg":"cat_ads.jpg","c_id":"25","fk_group_id":"7","cat_name":"cat_name","c_status":"1","type_for_group":"1","img":"9.jpg","src":"asset\/img\/main"},{"gid":"7","gtype":"1","g_name":"a","gstatus":"1","gad_stat":"0","gsrc":"asset\/img\/cat\/","gimg":"cat_ads.jpg","c_id":"26","fk_group_id":"7","cat_name":"cat_name","c_status":"1","type_for_group":"1","img":"9.jpg","src":"asset\/img\/main"}]
You did small mistake in model. However it should be: $this->db->select('cat_group.*, cat.*'); $this->db->from('cat'); $this->db->join('cat_group', 'cat.fk_group_id = cat_group.gid','all')->where('cat_group.gstatus = 1'); return $this->db->get()->result(); It must return all the rows of cat where fk_groupd_id = gid. Now you should parse the json result. UPDATE: $.ajax({ type: "POST", url: 'YOUR_URL', dataType:'JSON', success: function(data) { $.each(data, function(index, element) { //console.log(index); //alert(element.c_id); console.log(element.c_id); console.log(element.cat_name); // here console.log() is used to debug the data. }); } }) It's up to you now how you will display the data in HTML. You can check this example as how to parse json object and display them into DOM: how to parse json data with jquery / javascript?
JQuery returning [object Object]
I'm doing an calendar, and i created a page to show the events from a certain day. I'm using Ajax because i dont want my users to reload the page everytime that a new event is created. So, i'm using Json encode to get the values from an array, and everytime that i print a day with two events, i receive this: [{"event_day":"9","event_name":"test"}, {"event_day":"9","event_name":"test2"}] But when i try to print the elements in JQuery to put inside an element, i receive [object Object] I inserted the array inside a while loop because i'm getting multiple rows from my database table. PHP function function eventPrint($list_day, $month, $year){ $select = mysql_query("SELECT * FROM events WHERE event_day = '".$list_day."' AND event_month = '".$month."' AND event_year = '".$year."'") or die(mysql_error()); $data = array(); while($row = mysql_fetch_assoc($select)) { $event_day = $row['event_day']; $event_name = $row['event_name']; $data[] = array('event_day' => $event_day, 'event_name' => $event_name ); } echo json_encode($data); } Ajax $.ajax({ type: 'get', url: "modules/groups/new.php", data: { 'list_day': getday, 'month': getmonth, 'year': getyear, 'action': 'selection' }, success: function (response) { var obj = jQuery.parseJSON(response); $('.' + getmonth).html(obj.event_day); } });
Your code should be: success: function( response ) { var obj = response[0] ? response : jQuery.parseJSON(response); $('.' + getmonth).html(obj[1].event_day);
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.