Click vs Load in Ajax Call? - javascript

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;
}

Related

How to append a element that have more childs?

i need to append a table but i do it the wrong way.. I have this:
$("#times").append('<table id="departure_' + i + '" width="50%"> <tbody><tr><td>' + data.times[i].destination.name + '</td><td id="appendLate' + i + '">' + time + '</td><td>' + data.times[i].track + '</td><td>' + data.times[i].train_type + '</td><td>' + data.times[i].company + '</td></tr></tbody></table>');
this masive line make no table but alot of tabels.. hard to style.
how can i fix this?
see in action here: http://codepen.io/shiva112/pen/JGXoVJ?editors=001
The problem is that you are appending the whole table in a for statement. You should do something like this
// Select or create a table here
var table = $("#my-target-table");
var tableContent = "";
for (var i = 0; i < data.times.length; ++i) {
tableContent += '<tr><td>' + data.times[i].destination.name + '</td><td id="appendLate' + i + '">' + time + '</td><td>' + data.times[i].track + '</td><td>' + data.times[i].train_type + '</td><td>' + data.times[i].company + '</td></tr>'
}
table.find('tbody').html(tableContent);

Getting duplicates in my datatable

I'm new to JavaScript.
I only have three entries in my database but when I run the code listed below I get six results. One entry shows up 3x while the other two entries show up 2x. What might I be doing wrong?
var tidyAppts='';
query.find({
success: function(results) {
// Do something with the returned Parse.Object values
for (var i = 0; i < results.length; i++) {
var object = results[i];
//alert(object.id + ' - ' + object.get('ZipCode'));
tidyAppts+='<tr><td>'
+ object.get('Name') + '<td><td>'
+ object.get('Phone') + '<td><td>'
+ object.get('Address') + '<td><td>'
+ object.get('ZipCode') + '<td><td>'
+ object.get('Frequency') + '<td><td>'
+ object.get('TIDY') + '</td><td>'
+ object.get('FirstTIDYDay') + '</td><td>'
+ object.get('TIDYTime') + '</td><td>'
+ object.get('SecondTIDYDay') + '</td><td>'
+ object.get('SecondTIDYApptTime') + '</td><td>'
+ object.get('ThirdTIDYDay') + '</td><td>'
+ object.get('ThirdTIDYApptTime') + '</td></tr>';
(function($) {
$('#tidy-appt-table').append(tidyAppts);
})(jQuery);
}
},
When I used this code, only the first 4 objects for each entry is displayed in the table but I get the correct amount of records which is 3.
(function($) {
$('#tidy-appt-table').append('<tr><td>'
+ object.get('Name')
+ '</td><td>'
+ object.get('Phone')
+ '</td><td>'
+ object.get('Address')
+ '</td></td>'
+ object.get('ZipCode')
+ '</td></td>'
+ object.get('Frequency')
+ '</td></td>'
+ object.get('TIDY')
+ '</td><td>'
+ object.get('FirstTIDYDay')
+ '</td><td>'
+ object.get('TIDYTime')
+ '</td><td>'
+ object.get('SecondTIDYDay')
+ '</td></td>')
+ object.get('SecondTIDYApptTime')
+ '</td></td>'
+ object.get('ThirdTIDYDay')
+ '</td></td>'
+ object.get('ThirdTIDYApptTime')
+ '</td></tr>';
})(jQuery);
}
i figured it out I removed the plus sign from tidyAppts+='' and made it tidyAppts=

How to append all the elements at once to create a drop down in jQuery

I'm creating a drop down with three sub menus, so a main dropdown with publishers, a sub menu with authors (which are within that publisher) and a sub menu to authors containing the years they've been published. So hover over publisher, see authors in that publisher.
It worked fine but i've changed it to improve performance so instead of appending to the DOM each time i've been storing up the values in a variable and then appending to the DOM, however i'm now getting an error
cannot call method find of null
relating to the line:
var author = ulauthors.find('li.author[data-value="' + authorval + '"]');
Any ideas how i fix it, i guess because i'm not appending until near the end it can't find the element?
var target = $('#listpublishers');
$(info.genres).each(function (i) {
var genreval = this.genre;
var catval = this.genreGroup;
$(this.publishers).each(function (j) {
var publisherval = this.publisher;
var ulauthors = null;
var publisher = target.find('>li.publisher[data-value="' + publisherval + '"]');
var ulyears = null;
var publisherstring = '';
var targetstring = '';
var ulauthorstring = '';
var authorstring = '';
var ulyearstring = '';
//if publisher does not exist create it else find it
if (publisher.size() == 0) {
targetstring += '<li class="publisher" data-value="' + publisherval + '"><a onclick="gotoSubMenu">' + publisherval + '</a>';
target.append(targetstring)
publisherstring += '<ul class="sub-menuoos" data-title="publishers></ul>';
publisher.append(publisherstring)
} else {
ulauthors = publisher.find('>ul');
}
$(this.authors).each(function () {
var authorval = this.author + ' (' + genreval + ')';
var author_val = this.author;
var author = ulauthors.find('li.author[data-value="' + authorval + '"]');
if (author.size() == 0) {
ulauthorstring += '<li class="author" data-value="' + authorval + '"><a onclick="gotoSubMenu">' + authorval + '</a>';
ulauthors.append(ulauthorstring)
authorstring += '<ul class="sub-menuoos" data-title="authors></ul>';
author.append(authorstring);
} else {
ulyears = author.find('>ul');
}
$(this.publishedYears).each(function () {
var yearval = this;
var year = ulyears.find('li.year[data-value="' + yearval + '"]');
if (year.size() == 0) {
var id = ++count;
ulyearstring += '<li class="year" data-value="' + yearval + '"><a class="item" id="year"' + id + '"data-year="' + yearval + '" data-publisher="' + publisherval + '" data-author+"' + author_val + '" data-genre="' + genreval + '">' + yearval + '</a>';
ulyears.append(year);
}
});
});
});
});
});

Create rowspans with jquery

I append the data from a json-object to a table:
var array1 = $.map(data, function (field, i)
{
return '<tr><td>' + field.date + '</td><td>' + field.art + '</td><td class="san' + field.art +'">' + field.text + '</td></tr>';
});
$('#TableBody').append(array1.join(''));
Actually this works pretty good and i get a output like this:
<tbody id="TableBody">
<tr><td>18.02.2014</td><td>D</td><td class="sanD">Was soll ich sagen</td></tr>
<tr><td>18.02.2014</td><td>DD</td><td class="sanDD">hallo</td></tr>
<tr><td>17.02.2014</td><td>R</td><td class="sanR">Erster Versuch</td></tr>
</tbody>
But i would like to have such an output: Means that same field.date have only one row:
<tbody id="TableBody">
<tr><td rowspan="2">18.02.2014</td><td>D</td><td class="sanD">Was soll ich sagen</td></tr>
<tr><td>DD</td><td class="sanDD">hallo</td></tr>
<tr><td>17.02.2014</td><td>R</td><td class="sanR">Erster Versuch</td></tr>
</tbody>
How can i achieve this? Thanks
Fiddle: http://jsfiddle.net/V2mmw/2/
Here is a function that does what you want:
function mergeSameDates() {
var $firstItem,
sameCount = 0;
$("#TableBody tr td:nth-child(1)").each(function (index, item) {
var $item = $(item);
if ($firstItem === undefined || $item.text() !== $firstItem.text()) {
$firstItem = $item;
sameCount = 1;
} else {
sameCount += 1;
$firstItem.attr("rowspan", sameCount);
$item.remove();
}
});
}
Here is an updated demo fiddle.
I think that you need something like this, but i used $.each function:
var html = "";
var arr = new Array();
$.each(data, function (i, field) {
var rowspanTest = $.grep(data, function (elem) {
return elem.date === field.date;
}).length;
if(jQuery.inArray( field.date, arr ) == -1){
html += '<tr><td rowspan=' + rowspanTest + '>' + field.date + '</td><td>' + field.art + '</td><td class="san' + field.art +'">' + field.text + '</td></tr>';
arr.push(field.date);
}else{
html += '<tr><td>' + field.art + '</td><td class="san' + field.art +'">' + field.text + '</td></tr>';
}
});
$('#TableBody').append(html);
Demo JSFiddle

JavaScript undefined? [closed]

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');
}
});

Categories