populating data in two html tables using two ajax calls - javascript

i'm trying to populate two tables using two separate ajax calls. following is my code.
var payload = "authUserName=admin&authPassword=admin";
$.ajax({
url: "https://appserver.dev.cloud.wso2.com/t/madusanka/webapps/projecttracker-default-SNAPSHOT/services/projecttracker/userservice/user/1/projects",
type: "POST",
async: false,
dataType: "json",
data: payload,
complete: function(data) {
alert("complete " + JSON.stringify(data));
// for(var i = 1; i<= data.projects.project.length; i++){
// var tableRow = "<tr><td>" + data.projects.project[i].projectName + "</td><td>" + data.projects.project[i].startDate + "</td><td>" + data.projects.project[i].endDate + "</td><td>" + data.projects.project[i].statusId + "</td><td>" + "delete" + "</td></tr>";
// $("#projectListTable tbody:last").append(tableRow);
// }
}
}).then(function(data) {
alert("started");
var payload2 = "authUserName=admin&authPassword=admin";
$.ajax({
url: "https://appserver.dev.cloud.wso2.com/t/madusanka/webapps/projecttracker-default-SNAPSHOT/services/projecttracker/userservice/user/1/projects",
type: "POST",
async: false,
dataType: "json",
data: payload2
}).then(function(data) {
alert("ended");
for(var i = 1; i<= data.projects.project.length; i++){
var tableRow = "<tr><td>" + data.projects.project[i].projectName + "</td><td>" + data.projects.project[i].startDate + "</td><td>" + data.projects.project[i].endDate + "</td><td>" + data.projects.project[i].statusId + "</td><td>" + "delete" + "</td></tr>";
$("#userTable tbody:last").append(tableRow);
}
});
});
If i run above code as it is it will execute well and execute whatever functions in "then".
When i uncomment the commented for loop, it won't execute beyond that for loop. after populating project list table it simply stop executing. therefore "then" functions won't get executed. it seems only one table data population loop can be there.
I want both tables to be populated one after other using ajax. I'm really confused about this. Can someone point me in correct direction?

Why do you need to have both complete and then callback functions? Looking at your codes, they don't seem to do anything different. You might as well just merge them like this:
var payload = "authUserName=admin&authPassword=admin";
$.ajax({
url: "https://appserver.dev.cloud.wso2.com/t/madusanka/webapps/projecttracker-default-SNAPSHOT/services/projecttracker/userservice/user/1/projects",
type: "POST",
dataType: "json",
data: payload,
complete: function(data) {
alert("complete " + JSON.stringify(data));
for(var i = 1; i<= data.projects.project.length; i++){
var tableRow = "<tr><td>" + data.projects.project[i].projectName + "</td><td>" + data.projects.project[i].startDate + "</td><td>" + data.projects.project[i].endDate + "</td><td>" + data.projects.project[i].statusId + "</td><td>" + "delete" + "</td></tr>";
$("#projectListTable tbody:last").append(tableRow);
$("#userTable tbody:last").append(tableRow);
}
}
});

Related

jquery datatables "search" returns previously deleted data

Im using an onclick to delete selected rows from sql database and update the datatable simultaneously by sending an ajax to the php/server.
Responsible for deleting the record is some backend php.
So far so good.
However,when i try to search,it returns back the rows i have deleted,what should i do ?
$(document).on('click', '#delete', function() {
var id = $(this).parent().find("#id").text();
var name = $(this).parent().find("#name").text();
if(confirm("Are you sure you want to delete record " + id + " with name " + name + " ?")){
$.ajax({
method: "POST",
url: "http://localhost/indexDB/actions.php",
data: {
id: id,
deletename: name
}
})
.done(function(msg) {
alert(msg);
$("#dtVerticalScrollExample tbody").empty(); //EMPTY THE DB WINDOW
$.ajax({ //POPULATE DB WINDOW AGAIN
url: 'http://localhost/indexDB/ajaxfile.php',
type: 'get',
dataType: 'JSON',
success: function(response){
var len = response.length;
for(var i=0; i<len; i++){
var id = response[i].id;
var name = response[i].name;
var contents = response[i].contents;
var date = response[i].date;
var ajaxbutton = response[i].button;
var button = document.createElement("i");
button.className = "far fa-trash-alt trashdb";
var tr_str = "<tr>" +
"<td id=id>" + id + "</td>" +
"<td id=name>" + name + "</td>" +
"<td id=date>" + date + "</td>" +
"<td id=buttonrow>" + button.outerHTML + "</tr>";
$("#dtVerticalScrollExample tbody").append(tr_str);
}
}
});
});
}else{
alert("Delete cancelled !")
}
}); //DELETE RECORDS FROM DB

filter duplicate rows with cake php and java script

I'm trying to filter table which is append using java script with cake php frame work .
and the following code is for adding this tables when i have click on add new magazine ,, but the problem is that , It's add double rows which has been added before . So i need to filter the added rows to delete the duplicated row.
/// function to show magazines data table
$('#add_researches_button').click(function () {
$("input[name='bstock_researchs_id[]']:checked").each(function (i) {
val[i] = $(this).val();
});
$.ajax({
type: "POST",
url: '../BstockIn/getResearchesIds/' + val,
dataType: "json",
success: function (data) {
$('#researches').css('display', 'block');
var res = $.parseJSON(data);
var CountResearches = 0;
jQuery.each(res, function (index, value) {
CountResearches++;
$("#researches").append("<tr><td>"
+ value.research_serial +
"</td><td>"
+ value.research_release_date +
"</td><td>"
+ value.research_release_hejry_date +
"</td><td>"
+ value.research_pages +
"</td><td>"
+ value.research_copies +
"</td></tr>"
);
});
/// function to show magazines data table
$('#add_researches_button').click(function() {
$("input[name='bstock_researchs_id[]']:checked").each(function(i) {
val[i] = $(this).val();
});
$.ajax({
type: "POST",
url: '../BstockIn/getResearchesIds/' + val,
dataType: "json",
success: function(data) {
$('#researches').css('display', 'block');
var res = $.parseJSON(data);
var CountResearches = 0;
jQuery.each(res, function(index, value) {
CountResearches++;
if ($("#researches tr[data-id='" + value.research_serial + "']").length == 0)
$("#researches").append("<tr data-id='" + value.research_serial + "'><td>" +
value.research_serial +
"</td><td>" +
value.research_release_date +
"</td><td>" +
value.research_release_hejry_date +
"</td><td>" +
value.research_pages +
"</td><td>" +
value.research_copies +
"</td></tr>"
);
});

How to apply style sheet on dynamic generate radio button?

here, I am using form wizard. Using ajax to load the data and data are append in html.
ajax code :
$.ajax({
url: '<?php echo base_url(); ?>booking/listSiteUrl',
type: 'post',
dataType: 'json',
success: function (response) {
if (response.success == 1) {
var row = '';
var i = 1;
$.each(response.row_data, function (index, value) {
row += "<tr><td>" + i + "</td><td>" + value.url + "</td><td>" + value.p1_name + "</td><td hidden>" + value.id + "</td><td hidden>" + value.f_n + "</td><td><div class='radio-list'><label><input type='radio' id='f_n_val' name='select_val' data-url='" + value.url + "' data-pub='" + value.p1_name + "' data-id='" + value.id + "' data-follow='" + value.f_n + "' required='required'></label></div></td></tr>";
i++;
});
$("#results").html(row);
// $("input[type=radio]").uniform();
} else {
var row = '';
row += "<tr><td colspan='4' class='text-center'>No Records Found</td></tr>";
$("#results").html(row);
}
}
});
How to apply style sheet on a radio button? you can show in image very clearly...
When I am using uniform style i.e. ($("input[type=radio]").uniform();) work fine and radio button style is applied bt problem in when I am checking validation that time it will look like in below image :
Please help me to find out the way to solve this.
You can create your class in css as
.myradio{
// your code here
}
and then
$("input[type=radio]").addClass('myradio');

Selecting a row in a html table

I am trying to select a row in a table I have created and need use the values. The issue I am having is I created it using doms in javascript and got the values from a stored procedure which then populates the table.
so i use a simple div with an id -
<div id="Tab1" class="tab-pane fade in active"></div>
to create the table and populate it i use an ajax call -
function GetcarData() {
$.ajax({
type: "post",
data: JSON.stringify({
price: slidval,
}),
url: "/index.aspx/GetData",
dataType: "json",
contentType: "application/json",
success: function (object) {
responseData(object);
},
complete: function (object) {
},
error: function (object) {
}
});
}
function responseData(object) {
var stringed = JSON.stringify(object.d)
var arr = JSON.parse(stringed);
var i;
var out = "<table id='table' class='table table-striped'>";
var rowHeader = $("<tr></tr>").appendTo(out);
out += "<td><font size='4'>Make</font></td>";
out += "<td><font size='4'>Model</font></td>";
out += "<td><font size='4'>Version</font></td>";
out += "<td><font size='4'>Engine</font></td>";
out += "<td><font size='4'>(AV)Price new</font></td>";
out += "<td><font size='4'>(Av)Price used</font></td>";
out += "<td><font size='4'>Image</font></td>"
for(i = 0; i < arr.length; i++) {
out += "<tr><td>" +
arr[i].Make +
"</td><td>" +
arr[i].Model +
"</td><td>" +
"£" + arr[i].version +
"</td><td>"+
arr[i].Engine_size +
"</td><td>" +
"£" + arr[i].price_new +
"</td><td>" +
"£" + arr[i].price_used +
"</td><td><img src="+arr[i].image_url+" width='150' height='100'>" +
"</td></tr>";
}
out += "</table>";
document.getElementById("Tab1").innerHTML = out;
}
Now the issue I have is I cant seem to select a row.
I tried
("#table tr").click(function(){
alert("selected");
});
but that did not work.
Anyhelp would be appreciated
You created a set of elements that weren't in the DOM when page and were only added after initial DOMContentLoaded
To listen for events on elements that are dynamically added, removed via JavaScript DOM manipulations, you need to use slightly different event listener.
$(document).on('%eventName%', '%selector%', function() { // do your stuff });

incorporating pagination in ajax json

I have a ajax json retrieving all query results in a div.I'm not sure how to introduce pagination though.
<script>
$(document).ready(function () {
var hdnIds = document.getElementById('<%= HiddenField1.ClientID %>').value;
$.ajax({
type: "POST",
url: "WebService1.asmx/GetEmployees",
data: "{userid: " + JSON.stringify(hdnIds) + " }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (list) {
$("#Something").append("<ul id='bullets' class='ul1'></ul>");
for (i = 0; i < list.d.length; i++) {
$("#bullets").append("<li class='li1'>"
+ "<div style='float:left; width:20%'>"
+ "<img id='image' src='Handler3.ashx?id=" + list.d[i].id + "' />"
+ "<p style='margin-left:2px; position:relative;color:DodgerBlue;font-size:small; font-style:bold'>" + list.d[i].UserName + "</p>"
+ "<p style='margin-left:2px; position:relative;color:DodgerBlue;font-size:small'>" + list.d[i].Created_on + "</p>"
+ "</div>"
+ "<div style='float:left; width:80%'>"
+ "<p class='p11'>" + list.d[i].Statusmes + "</p>"
+ "</div>"
+ "</li>");
}
},
error: function (e) {
$("#Something").html("There was an error retrieving records");
}
});
});
</script>
And html as
<div id="Something"></div>
ANy help will be greatly appreciated!
First, I would read up on javascript templating. There are a lot of libraries out there that will allow you to remove the bloated html code from your JS code so that it's easier to manage. Something like this: https://github.com/BorisMoore/jquery-tmpl.
After that, you should put the responsibility of pagination on the server side and let the JS/Ajax handle the calls to retrieve the data set. For instance:
//server side
var start = request.params.start //retrieve start index for data set
var limit = request.params.limit //retrieve max number of data set size
return db.Model.find({start: start, limit: limit, ...})
//client side JS/Ajax
//load first page 0-9
$.ajax({
url: '/my/data/url',
params: {
start: 0, //start at first record in db
limit: 10 //only return 10 results
}
}).success(function(data) {
//render data set using template
$.template('#my-data-template', data).renderTo('#someDiv');
});
//load second page 10-19
$.ajax({
url: '/my/data/url',
params: {
start: 10, //start at nth record in db
limit: 10 //only return 10 results
}
}).success(function(data) {
//render data set using template
$.template('#my-data-template', data).renderTo('#someDiv');
});
If I understand the question correctly, you already know about append which is what you need, but you need to change all your ids to classes since there will be more than 1 of them. Then, put all of the html you want to append into a string and just append that html.
HTML:
<div id = "parent">
<div class = "Something"></div>
</div>
JAVASCRIPT (replace to the success AJAX call):
var htmlList = "<div class = "Something"><ul class='bullets ul1'>";
for (i = 0; i < list.d.length; i++) {
htmlList += "<li class='li1'>"
+ "<div style='float:left; width:20%'>"
+ "<img id='image' src='Handler3.ashx?id=" + list.d[i].id + "' />"
+ "<p style='margin-left:2px; position:relative;color:DodgerBlue;font-size:small; font-style:bold'>" + list.d[i].UserName + "</p>"
+ "<p style='margin-left:2px; position:relative;color:DodgerBlue;font-size:small'>" + list.d[i].Created_on + "</p>"
+ "</div>"
+ "<div style='float:left; width:80%'>"
+ "<p class='p11'>" + list.d[i].Statusmes + "</p>"
+ "</div>"
+ "</li>");
}
htmlList += "</ul></div>";
$("#parent").append(htmlList);

Categories

Resources