I am writing an HTML page to make a GET call constructing the URL with HTTP request param (driverid) to my underlying microservice using AJAX and display results in tabular format in the corresponding divs like below:
<html>
<head>Driver App
</head>
<body>
<form name="submitform" id="submitform">
<input type="submit" value="Refresh">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
var driverid = get("driverid");
$('[name="submitform"]').submit(function (e) {
e.preventDefault();
$.ajax({
url: "http://localhost:7777/driver/" + driverid + "/ride",
dataType: 'json',
type: "GET",
success: function (result) {
//alert(result);
var waitingHtml = '<table>';
var ongoingHtml = '<table>'
var completedHtml = '<table>';
$.each(result.data, function (i, item) {
if (item.status == 0) {
var requestTime;
if (item.requestTime != 0) {
requestTime = new Date(item.requestTime);
}
var startDate;
if (item.startTime != 0) {
startDate = new Date(item.startTime);
}
var endDate;
if (item.endTime != 0) {
endDate = new Date(item.endTime);
}
trHTML += '<tr><td>' + item.requestId + '</td><td>' + item.customerId + '</td><td>' + requestTime + '</td><td>' + status + '</td><td>' + item.driverId + '</td><td>' + startDate + '</td><td>'
+ endDate + '</td></tr>';
});
trHTML +="</table>";
$("#WaitingHolder").html(trHTML);
} else if (item.status == 1) {
var requestTime;
if (item.requestTime != 0) {
requestTime = new Date(item.requestTime);
}
var startDate;
if (item.startTime != 0) {
startDate = new Date(item.startTime);
}
var endDate;
if (item.endTime != 0) {
endDate = new Date(item.endTime);
}
trHTML += '<tr><td>' + item.requestId + '</td><td>' + item.customerId + '</td><td>' + requestTime + '</td><td>' + status + '</td><td>' + item.driverId + '</td><td>' + startDate + '</td><td>'
+ endDate + '</td></tr>';
});
trHTML +="</table>";
$("#OngoingHolder").html(trHTML);
} else {
var requestTime;
if (item.requestTime != 0) {
requestTime = new Date(item.requestTime);
}
var startDate;
if (item.startTime != 0) {
startDate = new Date(item.startTime);
}
var endDate;
if (item.endTime != 0) {
endDate = new Date(item.endTime);
}
trHTML += '<tr><td>' + item.requestId + '</td><td>' + item.customerId + '</td><td>' + requestTime + '</td><td>' + status + '</td><td>' + item.driverId + '</td><td>' + startDate + '</td><td>'
+ endDate + '</td></tr>';
});
trHTML +="</table>";
$("#CompletedHolder").html(trHTML);
}
}
}
}).done (function(data) { });
});
</script>
<table>
<tr><th>Waiting</th><th>Ongoing</th><th>Completion</th><tr>
<tr>
<td><div id="WaitingHolder">
</div></td>
<td><div id="OngoingHolder">
</div></td>
<td><div id="CompletedHolder">
<div></td>
</tr>
</table>
</body>
</html>
Here are the sample data which I will be printing in the corresponding div blocks in tabular format:
{
"data": [
{
"requestId": 44,
"customerId": 234,
"requestTime": 1502652444000,
"status": 2,
"driverId": 5,
"startTime": 1502652444000,
"endTime": 1502652744000
},
{
"requestId": 52,
"customerId": 234234,
"requestTime": 1502658544000,
"status": 2,
"driverId": 5,
"startTime": 1502658544000,
"endTime": 1502658844000
}
]
}
On making the request, the page just loads with no error in console. Also there is no HTTP call made to the backend. I am not able to fix it with my limited HTML/JS expertise. Can someone help me in getting this fixed?
there are some logical errors in your code, i have sorted,
<html>
<head>Driver App
</head>
<body>
<form name="submitform" id="submitform">
<input type="submit" value="Refresh">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
var driverid = get("driverid");
$('[name="submitform"]').submit(function (e) {
e.preventDefault();
$.ajax({
url: "http://localhost:7777/driver/" + driverid + "/ride",
dataType: 'json',
type: "GET",
success: function (result) {
//alert(result);
var waitingHtml = '<table>';
var ongoingHtml = '<table>'
var completedHtml = '<table>';
$.each(result.data, function (i, item) {
if (item.status == 0) {
var requestTime;
if (item.requestTime != 0) {
requestTime = new Date(item.requestTime);
}
var startDate;
if (item.startTime != 0) {
startDate = new Date(item.startTime);
}
var endDate;
if (item.endTime != 0) {
endDate = new Date(item.endTime);
}
waitingHtml += '<tr><td>' + item.requestId + '</td><td>' + item.customerId + '</td><td>' + requestTime + '</td><td>' + status + '</td><td>' + item.driverId + '</td><td>' + startDate + '</td><td>'
+ endDate + '</td></tr>';
} else if (item.status == 1) {
var requestTime;
if (item.requestTime != 0) {
requestTime = new Date(item.requestTime);
}
var startDate;
if (item.startTime != 0) {
startDate = new Date(item.startTime);
}
var endDate;
if (item.endTime != 0) {
endDate = new Date(item.endTime);
}
ongoingHtml += '<tr><td>' + item.requestId + '</td><td>' + item.customerId + '</td><td>' + requestTime + '</td><td>' + status + '</td><td>' + item.driverId + '</td><td>' + startDate + '</td><td>'
+ endDate + '</td></tr>';
} else {
var requestTime;
if (item.requestTime != 0) {
requestTime = new Date(item.requestTime);
}
var startDate;
if (item.startTime != 0) {
startDate = new Date(item.startTime);
}
var endDate;
if (item.endTime != 0) {
endDate = new Date(item.endTime);
}
trHTML += '<tr><td>' + item.requestId + '</td><td>' + item.customerId + '</td><td>' + requestTime + '</td><td>' + status + '</td><td>' + item.driverId + '</td><td>' + startDate + '</td><td>'
+ endDate + '</td></tr>';
}
});
waitingHtml+='</table>';
$("#WaitingHolder").html(waitingHtml);
ongoingHtml+='</table>';
$("#OngoingHolder").html(ongoingHtml);
completedHtml+='</table>';
$("#CompletedHolder").html(completedHtml);
}
});
</script>
<div id="WaitingHolder"></div>
<div id="OngoingHolder"></div>
<div id="CompletedHolder"></div>
</body>
</html>
Related
Here's some sample JSON information below. I'm looking to display this information in a table using vanilla javascript from pullData variable, but the data is shown before I click my "Load Data" button.
{"id":6,"gender":"F","first_name":"Dorothy","last_name":"Watkins","email":"dwatkins5#elpais.com","active":false,"title":"Structural Analysis Engineer"},
{"id":7,"gender":"F","first_name":"Norma","last_name":"Johnston","email":"njohnston6#blogger.com","active":true,"title":"Help Desk Operator"},
{"id":8,"gender":"M","first_name":"Joe","last_name":"Andrews","email":"jandrews7#slashdot.org","active":true,"title":"VP Accounting"},
{"id":9,"gender":"M","first_name":"Jason","last_name":"Bryant","email":"jbryant8#oracle.com","active":true,"title":"VP Product Management"},
{"id":10,"gender":"F","first_name":"Kimberly","last_name":"Fox","email":"kfox9#time.com","active":true,"title":"Environmental Tech"},
Below I commented out getData.addEventListener because when it's onClick(), it doesn't appear to call the JSON data, whereas when it's onLoad() the data is sent immediately. What am I missing from this?
var pullData = document.getElementById("load").addEventListener('click',parseData);
var reset = document.getElementById("reset").addEventListener('click',resetData);
var dataURL= "./surveyData.php";
var getData = new XMLHttpRequest();
// getData.addEventListener('load',parseData);
getData.open('GET', dataURL);
getData.send();
function parseData(getEvent){
alert("test");
var myArray= JSON.parse(getEvent.target.responseText);
var output="";
for(i in myArray){
output+= '<tr><td>' + myArray[i].id + '</td><td>' + myArray[i].gender + '</td><td>' + myArray[i].first_name + '</td><td>' + myArray[i].last_name + '</td><td>' + myArray[i].email + '</td><td>' + myArray[i].active + '</td><td>' + myArray[i].title + '</td></tr>';
}
output +="</table>";
document.getElementById("grabby").innerHTML ="<table width=\"100%\" ><tr><td>ID</td><td>Gender</td><td>First Name</td><td>Last Name</td><td>E-Mail</td><td>Active</td><td>Title</td>" + output;
document.getElementById("reset").disabled=false;
document.getElementById("load").disabled=true;
}
function resetData(){
document.getElementById("grabby").innerHTML ="<table width=\"100%\" ><tr><td>ID</td><td>Gender</td><td>First Name</td><td>Last Name</td><td>E-Mail</td><td>Active</td><td>Title</td>";
document.getElementById("reset").disabled=true;
document.getElementById("load").disabled=false;
}
(Please don't show me Jquery :))
Send request after click and show data after response
document.getElementById('load').addEventListener('click', getAndShowData);
document.getElementById('reset').addEventListener('click', resetData);
var dataURL = './surveyData.php';
function getAndParseData() {
var getData = new XMLHttpRequest();
getData.addEventListener('load', showData);
getData.open('GET', dataURL);
getData.send();
}
function showData(getEvent) {
alert('test');
var myArray = JSON.parse(getEvent.responseText);
var output = '';
for (i in myArray) {
output += '<tr><td>' + myArray[i].id + '</td><td>' + myArray[i].gender + '</td><td>' + myArray[i].first_name + '</td><td>' + myArray[i].last_name + '</td><td>' + myArray[i].email + '</td><td>' + myArray[i].active + '</td><td>' + myArray[i].title + '</td></tr>';
}
output += '</table>';
document.getElementById('grabby').innerHTML = '<table width="100%"><tr><td>ID</td><td>Gender</td><td>First Name</td><td>Last Name</td><td>E-Mail</td><td>Active</td><td>Title</td>' + output;
document.getElementById('reset').disabled = false;
document.getElementById('load').disabled = true;
}
function resetData() {
document.getElementById('grabby').innerHTML = '<table width="100%" ><tr><td>ID</td><td>Gender</td><td>First Name</td><td>Last Name</td><td>E-Mail</td><td>Active</td><td>Title</td>';
document.getElementById('reset').disabled = true;
document.getElementById('load').disabled = false;
}
I am populating a html table using an Ajax call. Every time I click on Upload button which re-populates the table, the top header row shifts right. How can I ensure it actually does not happen ?
HTML -
<input type="button" id="upload" value="Upload" class="btn btn-primary custom-button-width .navbar-right" />
<div id="hello" style="position: relative; margin-top: -10px; overflow: auto; width: 100%; max-height: 550px; align-self: center; overflow: auto;">
</div>
JS-
function populateTable(finalObject) {
var headers1 = ["Name1","Name2","Name3","Name4","Name5","Name6",
"Name7","Name8","Name9","Name10",
];
var obj = resp;
var table = $("<table id='my-table' />");
headers1.splice(6, 0, "New Name");
var columns = headers1;
columns.unshift('');
var columnCount = columns.length;
var thead = $('<thead/>');
var row_head = $('<tr/>');
for (var i = 0; i < columnCount; i++) {
var headerCell = $("<th/>");
if (i == 0) {
headerCell.html("<span id='sort'>キャンセル</span>");
}
else if (i == 15|| i==17) {
headerCell.html([columns[i]]);
headerCell.addClass("sortable");
}
else {
headerCell.html([columns[i]]);
}
row_head.append(headerCell);
}
thead.append(row_head);
table.append(thead);
var tbody = $('<tbody/>');
$.each(obj, function (i, obj) {
var row = '<tr ><td><input type="checkbox" value=' + obj.Name1 + '></td><td>' + ReplaceNull(obj.Name2) + '</td><td>' + ReplaceNull(obj.Name3) + '</td><td>'
+ ReplaceNull(obj.Name4) + '</td><td>' + ReplaceNull(obj.Name5) + '</td><td>' + ReplaceNull(obj.Name6) + '</td><td>' + ReplaceNull(obj.Name7) + '</td><td>'
+ ReplaceNull(obj.Name8) + '</td><td>' + ReplaceNull(obj.9) + '</td><td>' + ReplaceNull(obj.10) + '</td><td>' + ReplaceNull(obj.DisPoNumber1) + '</td><td>' + ReplaceNull(obj.DisPoNumber2) + '</td><td><input name=' + ReplaceNull(obj.Name1) + ' id=in' + ReplaceNull(obj.Name2) + ' type="text" size=15 placeholder="Enter Replacement name" value=' + ReplaceNull(obj.New_Name) + '></td></tr>';
tbody.append(row)
});
table.append(tbody);
var dvTable = $("#hello");
dvTable.html("");
dvTable.append(table);
Ajax -
$.ajax({
type: "GET",
url: '',
async: true,
dataType: "json",
contentType: "application/json; charset= UTF-8",
success: function (response) {
populateTable(glResp);
},
error: function (error) {
console.log(error);
alert("Error in the file format!!");
}
});
I have some divs which are generated by jquery. Inside there is showing up the price, the title and the selected option value.
I've tried a lot of things to hide each div class "result" if no option is select, but with no luck.
Is there a way to hide each div without rewriting the whole code?
JS:
function pcc_calc_forms() {
jQuery(".calcolare").each(function (e) {
var t = jQuery(this).attr("id");
var n = pcc_form_data(t);
jQuery("#" + t + "-mostra").html('<h3 class="pcc-total">Totale : ' + n[0] + "" + "€" + '</h3><div class="content">' + n[1] + '<br /><br /></div>')
})
}
function pcc_form_data(e) {
var t = new Array(0, "");
var n = new Array;
var r = new Array;
$("#" + e + " select").each(function (e) {
var title = $(this).attr("data-title");
var inside = $(this).find("option:selected").attr("data-title");
var i = $(this).find("option:selected").html();
if (inside === undefined) {
inside = " ( " + i + " ) "
} else {
inside = " ( " + inside + " ) "
}
var i = $(this).find("option:selected").attr("data-price");
var s = parseFloat($(this).attr("data-mult"));
if (isNaN(s)) {
s = 1
}
var o = parseFloat($(this).find("option:selected").text());
if (isNaN(o)) {
o = 0
}
if (i !== undefined) {
if (i == "this") {
i = o
} else {
i = parseFloat(i)
}
t[0] = t[0] + parseFloat(i) * s;
if (s == 1) {
t[1] = t[1] + "<div class=\"result\"><b>" + title + "" + inside + "</b> : " + parseFloat(i) + "" + " € " + "</div>"
} else {
t[1] = t[1] + "<div class=\"result\"><b>" + title + "" + inside + "</b> : " + parseFloat(i) + " X " + s + " = " + parseFloat(i) * s + "" + " € " + "</div>"
}
}
});
n = [];
r = [];
return t
}
$(document).ready(function () {
pcc_calc_forms();
$(document).on("change", ".calcolare select", function () {
pcc_calc_forms()
});
});
THIS is the link to the fiddle
Thanks in advance for any hint.
$(document).on("change", ".calcolare select", function () {
var i = $(this).find('option:selected').index();
alert(i);
//if(i>0) ppc_calc_forms();
//else $('.results').hide();
})
This will find the index of the selected option... as you can see, it works, just not with your function...
I would simplify that script as much as possible..
I understand not wanting to rewrite the code substantially at this point. However, for comparison, here is the way I would do it while still holding to your general pattern:
function pcc_calc_forms() {
jQuery(".calcolare").each(function (e) {
var t = jQuery(this).attr("id");
var items = pcc_item_data(t);
var totalPrice = $.makeArray(items).reduce(function(total,item,i,a) {
return total+item.price;
},0);
text = '<h3 class="pcc-total">Totale : ' + totalPrice + "" + "€" + '</h3>';
text += '</h3><div class="content">';
items.each(function(i,item) {
if (item.mult > 1)
text += "<div class=\"result\"><b>" + item.title + " ( " + item.name + " )</b> : " + item.price + " X " + item.mult + " = " + item.price * item.mult + "" + " € " + "</div>";
else
text += "<div class=\"result\"><b>" + item.title + " ( " + item.name + " )</b> : " + item.price + "" + " € " + "</div>";
});
text += '<br /><br /></div>';
jQuery("#" + t + "-mostra").html(text);
});
}
function pcc_item_data(e) {
return $("#" + e + " select").map(function (e) {
if (this.selectedIndex > 0) {
var item = {};
item.title = $(this).attr("data-title");
var inside = $(this).find("option:selected").attr("data-title");
var i = $(this).find("option:selected").html();
item.name = inside ? inside : i;
item.price = parseFloat($(this).find("option:selected").attr("data-price"));
var mult = parseFloat($(this).attr("data-mult"));
item.mult = isNaN(mult) ? 1 : mult;
return item;
}
});
}
$(document).ready(function () {
pcc_calc_forms();
$(document).on("change", ".calcolare select", function () {
pcc_calc_forms();
});
});
What I've done:
Separate data collection (pcc_item_data) from data presentation;
this makes the code more readable and easier to maintain later.
Used map (http://api.jquery.com/jQuery.map/) and reduce (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce) to transform / aggregate arrays; they're concise
and expressive once you're familiar with them.
How can I get loaded filename? I have to put this instead of header, but I don't know how. I've tried to add additional parameter to xmlParser function, but actually it didn't work for me. Here is my code:
$(document).ready(function () {
doAJAX('LoadedFile1.xml');
doAJAX('LoadedFile2.xml');
});
function doAJAX(url) {
$.ajax({
type: "GET",
url: url,
dataType: "xml",
success: xmlParser
});
}
function xmlParser(xml) {
$('#load').fadeOut();
var myDate = new Date();
var currentdate = new Date();
var n =
currentdate.getFullYear()
+ ("0" + (currentdate.getMonth() + 1)).slice(-2)
+ ("0" + currentdate.getDate()).slice(-2)
+ ("0" + currentdate.getHours()).slice(-2)
+ ("0" + currentdate.getMinutes()).slice(-2)
+ ("0" + currentdate.getSeconds()).slice(-2);
var x = false;
var y = false;
$(xml).find("programme").each(function () {
if ((parseFloat(n) > (parseFloat($(this).attr("start").slice(0,-6)))) && (parseFloat(n) < (parseFloat($(this).attr("stop").slice(0,-6)))))
{
$(".main").append('<div class="header">HEADER</div><div class="programme"><div class="title">' + $(this).find("title").text() + '</div><div class="timec">' + n + '</div><div class="time">' + $(this).attr("start").slice(0,-6) + '</div><div class="time">' + $(this).attr("stop").slice(0,-6) + '</div><div class="description">' + $(this).find("desc").text() + '</div><div class="date">Published ' + $(this).find("category").text() + '</div>');
x = true;
}
else if ( x == true && y == true)
{
$(".main").append('<div class="programme"><div class="title">' + $(this).find("title").text() + '</div><div class="timec">' + n + '</div><div class="time">' + $(this).attr("start").slice(0,-6) + '</div><div class="time">' + $(this).attr("stop").slice(0,-6) + '</div><div class="description">' + $(this).find("desc").text() + '</div><div class="date">Published ' + $(this).find("category").text() + '</div></div>');
x = false;
}
y = true;
$(".programme").fadeIn(1000);
});
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
UPDATED CODE
CURRENT ERROR: Uncaught TypeError: Cannot read property 'id_cursa' of undefined
I really don't know which may be the problem ???
function locurilibere(data, callback) {
var URL = Path + 'rezervaribilete/locurilibere/' + data;
$.get(URL, function(obj) {
if (obj.raspuns === "nu") {
callback(true);
} else {
callback(false);
}
}, 'json');
}
function populateCurseDus(de_la, pana_la, data_plecarii) {
var data = de_la + "-" + pana_la + "-" + data_plecarii;
$.get(Path + 'rezervaribilete/listCurseDus/' + data, function(o) {
for (var i = 0; i < o.length; i++) {
var id_cursa = o[i].id_cursa;
var datalocuri = id_cursa + "-" + data_plecarii;
locurilibere(datalocuri, function(result){
if (result) {
$('#cursedus tbody').append('<tr style="background:red;"><td><input type="radio" name="id_cursadus" value="' + o[i].id_cursa + '" disabled></td><td>' + o[i].cod_cursa + '</td><td>' + o[i].de_la + '</td><td>' + o[i].pana_la + '</td><td>' + o[i].ora_plecare + '</td><td>' + o[i].ora_sosire + '</td><td>' + o[i].id_transportator + '</td><td>' + o[i].id_traseu + '</td></tr>');
} else {
$('#cursedus tbody').append('<tr><td><input type="radio" name="id_cursadus" value="' + o[i].id_cursa + '"></td><td>' + o[i].cod_cursa + '</td><td>' + o[i].de_la + '</td><td>' + o[i].pana_la + '</td><td>' + o[i].ora_plecare + '</td><td>' + o[i].ora_sosire + '</td><td>' + o[i].id_transportator + '</td><td>' + o[i].id_traseu + '</td></tr>');
}
});
}
}, 'json');
}
It will not work as expected because of asynchronous nature of ajax request, you a callback to fix it
function freeseats(data, callback) {
var URL = Path + 'bookings/freeseats/' + data;
$.get(URL, function(obj) {
if (obj.raspuns === "nu") {
// alert("no");
callback(true);
} else {
// alert("yes");
callback(false);
}
}, 'json');
}
// ********************************* second
// **************************************
function populateDepartures(from, to, departure) {
var data = from + "-" + to + "-" + departure;
$.get(Path + 'booking/listDepartures/' + data, function(o) {
$.each(o, function(index, item) {
var id_flight = item.id_flight;
var dataseats = id_flight + "-" + departureDate;
freeseats(dataseats, function(result) {
if (result) {
alert("no more seats");
$('#cursedus tbody')
.append('<tr style="background:red;"><td><input type="radio" name="id_cursadus" value="'
+ item.id_cursa
+ '" disabled></td><td>'
+ item.cod_cursa
+ '</td><td>'
+ item.de_la
+ '</td><td>'
+ item.pana_la
+ '</td><td>'
+ item.ora_plecare
+ '</td><td>'
+ item.ora_sosire
+ '</td><td>'
+ item.id_transportator
+ '</td><td>'
+ item.id_traseu + '</td></tr>');
} else {
alert("there are free seats");
$('#cursedus tbody')
.append('<tr><td><input type="radio" name="id_cursadus" value="'
+ item.id_cursa
+ '"></td><td>'
+ item.cod_cursa
+ '</td><td>'
+ item.de_la
+ '</td><td>'
+ item.pana_la
+ '</td><td>'
+ item.ora_plecare
+ '</td><td>'
+ item.ora_sosire
+ '</td><td>'
+ item.id_transportator
+ '</td><td>'
+ item.id_traseu + '</td></tr>');
}
});
});
}, 'json');
}
i think I have deciphered what you need. Please take a look at this jsFiddle Link and see if this serves your question.
Here's the code:
var boolFlag = false;
var firstFunc = function (){
if(boolFlag === false){
boolFlag = true;
return 'yes';
}else{
boolFlag = false;
return 'no';
}
};
var secondFunc = function () {
return firstFunc();
};
$('#myButton').click(function (){
if(secondFunc() == 'yes'){
console.log('hello world, you said: YES');
}else{
console.log('hello universe, you said: NO');
}
});