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.
Related
When I click my <select> tag, then it sends an AJAX request to the server script, which returns an array of values, which then populate the dropdown. My code is as following:
HTML:
<p id="cln_cd">Colony code : <select name="colony_code" id="colony_code" style="max-width:90%;" onclick="get_code()">
<option value="" selected="selected_code">Select your colony code</option>
</select></p>
JS:
function get_code(){
var select = document.getElementById("colony_code");
$.ajax({
url : 'index_backend.php',
type : 'POST',
data : {"input":"code"},
success : function(response) {
var parsedResponse = JSON.parse(response);
parsedResponse = parsedResponse.filter( function( item, index, inputArray ) {
return inputArray.indexOf(item) == index;
}); //removes duplicates
for(var i=0; i<parsedResponse.length; i++){
var opt = parsedResponse[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
},
complete: function(){
}
});
}
Now, the more I press the <select> tag, the more the same data keeps on populating my dropdown menu.
To prevent this, I tried emptying my dropdown list before inserting data into it, like this:
function removeOptions(selectElement) {
var i, L = selectElement.options.length - 1;
for(i = L; i >= 1; i--) {
selectElement.remove(i);
} //only the "Select your colony code" stays as default, rest is removed
}
function get_code(){
var select = document.getElementById("colony_code");
removeOptions(select);
$.ajax({
url : 'index_backend.php',
type : 'POST',
data : {"input":"code"},
success : function(response) {
var parsedResponse = JSON.parse(response);
parsedResponse = parsedResponse.filter( function( item, index, inputArray ) {
return inputArray.indexOf(item) == index;
}); //removes duplicates
for(var i=0; i<parsedResponse.length; i++){
var opt = parsedResponse[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
},
complete: function(){
}
});
}
Now, although my dropdown is not taking in duplicate values any more, but no matter what <option> value, I press, it just shows the Select your colony code option. I have no idea as to why this is happening. How do I fix this?
Firstly you have a mix of jQuery and plain JS methods in your code. It's best to stick to one or the other. As you've included the jQuery library in the page, you may as well stick with that to make the code more succinct.
With regard to the issue, I assume you're expecting to retain the current selected item when reloading the option elements. As such you need to save that value in a variable, remove the existing option, re-populate them and then re-assign the value. The code would look something like this:
function get_code() {
let $select = $("#colony_code");
$.ajax({
url: 'index_backend.php',
type: 'POST',
data: { "input": "code" }, // should 'code' be a variable...?
dataType: 'json', // add this property to avoid the need to call JSON.parse in success
success: function(response) {
let selectedValue = $select.val();
let html = response.filter((e, i, a) => a.indexOf(e) === i).map(item => `<option value="${item}">${item}</option>`);
$select.html(html).val(selectedValue);
},
complete: function() {}
});
}
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 have dropdown list of country suggestions and input above. When i click on one of them - AJAX should work(and it does) and add value to #msg_native. HTML:
echo '<div class="search_native"><input type="text" name="native_input" id="native"/>';
echo "<div id='output'></div></div>";
All JQUERY :
<script type="text/javascript">
$(document).ready(function() {
$("input").keyup(function(){
$array = ['usa','france','germany'];
$input_val = $("input[name='native_input']").val();
$('#output').text('')
r = new RegExp($input_val)
for (i = 0; i < $array.length; i++) {
if ($array[i].match(r)) {
$('#output').append('<p class="match">' + $array[i] + '</p>')
}
}
});
$(document).on('click', '.match', function(){
$value = $(this).text();
$('#native').val($value);
});
});
</script>
<script type="text/javascript">
$(function() {
$('#native').change(function() {
alert('cl');
$.ajax({
type: "POST",
url: "home.php",
dataType: 'json',
encode: true,
data: {native_input: $("input[name='native_input']").val()},
cache: false,
success: function(data){
alert(data);
$("#msg_native").after(data);
}});
return false;
});
});
</script>
The problem is that the value that gets posted is only what Ive typed myself, regardless on clicked element. But I want complete value- not only typed letters...so it firstly posts value and then 'finishes' the input (if clicked)
What can you practically advice to me?
data: {native_input: $value},
returns empty string
Some of this might be debatable but I put those in place for maintainability of the code and/or to match the most recent jQuery.
Only use one document ready handler (if possible)
Remove all the global objects (put var in front of them)
Use the native id when possible as fastest selector (not $("input[name='native_input']") for instance)
use this in the event handler, not the full selector (see next item)
If I enter "France" not "france" match does not work so need to case that input to equality var $input_val = $(this).val().toLowerCase();
You start with an empty field, might be good to show the match for that - simply trigger the keyup on startup to show all the array: }).trigger('keyup'); Now they are available for your clicking.
Attach the click handler on the wrapper for the "match" elements: $('#output').on('click', '.match', function() {
Use the promise form of the ajax .done(
Create a new custom event instead of the "change" on the native. We can then trigger that event as/when needed (the real issue you describe) Example: $('#native').trigger('myMatch'); and as I use it here:
trigger the event on a full match:
if (jQuery.inArray($input_val, $array) !== -1) {
$(this).trigger('myMatch');
}
Revised code:
$(document).ready(function() {
$("#native").on('keyup', function() {
var $array = ['usa', 'france', 'germany'];
var $input_val = $(this).val().toLowerCase();
$('#output').html('');
var r = new RegExp($input_val);
for (var i = 0; i < $array.length; i++) {
if ($array[i].match(r)) {
$('#output').append('<p class="match">' + $array[i] + '</p>');
}
}
// full match entered, trigger the match
if (jQuery.inArray($input_val, $array) !== -1) {
$(this).trigger('myMatch');
}
}).on('myMatch', function() {
alert('cl');
var nativeMatch = {
native_input: $("#native").val()
};
$.ajax({
type: "POST",
url: "home.php",
dataType: 'json',
encode: true,
data: nativeMatch,
cache: false
}).done(function(data) {
alert(data);
$("#msg_native").after(data);
});
return false;
}).trigger('keyup');
$('#output').on('click', '.match', function() {
var $value = $(this).text();
$('#native').val($value).trigger('myMatch');
});
});
I hope I can explain my issue clearly.
I am running a function to get values from a database using ajax, and adding each result as a row in a table. This is so the user can delete or edit any row they want. I'm adding IDs dynamically to the columns and also the edit and delete buttons which are generated. So it looks like this:
My code:
function getstationdata(){
var taildata1 = $('#tailnumber2').val();
var uid = $('#uid').val();
$.ajax({
// give your form the method POST
type: "POST",
// give your action attribute the value ajaxadd.php
url: "ajaxgetstationdata.php",
data: {tailnumber:taildata1, uid:uid},
dataType: 'json',
cache: false,
})
.success(function(response) {
// remove all errors
$('input').removeClass('error').next('.errormessage').html('');
// if there are no errors and there is a result
if(!response.errors && response.result) {
var trHTML = '';
$.each(response.result, function( index, value) {
trHTML += '<tr><td><input type="text" value="' + value[2] + '"></td><td><input type="text" class="weightinputclass"value="' + value[3] + '"></td><td><input type="text" class="arminputclass"value="' + value[4] + '"></td><td><input type="text" class="momentinputclass" value="' + value[5] + '"></td><td><button id="updatecgbtn" onclick="updatecg()"class="editbuttonclass">Edit</button></td><td><button id="deletecgbtn" class="deletebuttonclass"">Delete</button></td></tr>';
});
$('#mbtbody').html('');
$('#mbtbody').html(trHTML);
var ID = 0;
$('.weightinputclass').each(function() {
ID++;
$(this).attr('id', 'weightinputboxID'+ID);
});
var ID = 0;
$('.arminputclass').each(function() {
ID++;
$(this).attr('id', 'arminputboxID'+ID);
});
var ID = 0;
$('.momentinputclass').each(function() {
ID++;
$(this).attr('id', 'momentinputboxID'+ID);
});
var ID = 0;
$('.editbuttonclass').each(function() {
ID++;
$(this).attr('id', 'editbutton'+ID);
});
var ID = 0;
$('.deletebuttonclass').each(function() {
ID++;
$(this).attr('id', 'deletebutton'+ID);
});
} else {
// append the error to the form
$.each(response.errors, function( index, value) {
// add error classes
$('input[name*='+index+']').addClass('error').after('<div class="errormessage">'+value+'</div>')
});
}
});
}
The code I have when adding the info is in a form and it looks like this:
$('#addstations').on('submit', function(e){
e.preventDefault();
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
dataType: 'json',
cache: false,
})
.success(function(response) {
$('input').removeClass('error').next('.errormessage').html('');
if(!response.errors && response.result) {
$.each(response.result, function( index, value) {
chartdata4=(tailnumber3.value)
});
} else {
// append the error to the form
$.each(response.errors, function( index, value) {
// add error classes
$('input[name*='+index+']').addClass('error').after('<div class="errormessage">'+value+'</div>')
});
}
});
});
I searched a bit on the internet and found out that I can't add a form inside my table for each row which would have been easy to do and I can reuse my code which I use when adding new info.
So, can someone please point me in the right direction?
Here is the direction you could go
$('#formTable').on('click',"button" function(e){
var $row = $(this).closest("tr"), $form = $("#addstations");
var data = {
passenger:$row.find("passengerClass").val(),
weight :$row.find("weightClass").val()
} // no comma on the last item
data["type"]=this.className=="deletebuttonclass"?"delete":"edit";
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
dataType: 'json',
cache: false,
})
...
I assume that the problem is that you want to add a form as a child of a table / tbody element to wrap your row. You cannot do that and the browser will most likely strip the form tags, leaving you with nothing to serialize.
There are different solutions for that, for example:
Build the data object manually in javascript when a button on a row is clicked;
Use a non-form grid solution for your layout.
Add each row in its own table and have the form wrap that table
The third solution is a bit of a hack, I would use the first or the second myself.
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.