JavaScript undefined? [closed] - javascript

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

Related

Click vs Load in Ajax Call?

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

Making use of HTTP request param in GET call using AJAX

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>

Clearing list from partial view with javascript

I have a list that is created by a javascript function. I have a separate function to reset the page, but it will not clear the list that was created. Any thoughts?
Javascript call to create the list:
$(function submit() {
$('form').submit(function (e) {
e.preventDefault();
$("#searchResults").show();
$.ajax({
url: 'Home/TAPost',
data: $('form').serialize(),
dataType: "json",
type: 'POST',
success: function (accts) {
$("#rowHeaders").append('<tr><td>' + "Customer Name" + '</td><td>' + " Customer SSN" + '</td><td>' + " FHBOAT Account Number" + '</td><td>' +
" Original Account Number" + '</td><td>' + " Product Type" + '</td><tr>');
$.each(accts, function (index, acct) {
$("#resultsTable").append('<tr><td>' + acct.CustomerName + '</td><td>' + " " + acct.SSN + '</td><td>' + " " + acct.FHAcctNumber + '</td><td>'
+ " " + acct.OriginalAcctNumber + '</td><td>' + " " + acct.ProductType + '</td></tr>');
});
}
});
return false;
});
});
Call to reset:
function resetForm() {
document.getElementById("LOB").style.borderColor = "";
document.getElementById("LOB").style.borderColor = "";
$('#resultsTable').empty();
return false;
};
HTML:
<section id="searchResults">
<h2>Search Results</h2>
<table id="resultsTable" cellpadding="2" cellspacing="50">
<thead id="rowHeaders"></thead>
</table>
</section>
Instead of:
$('#resultsTable').empty();
You can use:
$('#resultsTable').html('');

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 return a value from javascript function [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I have the following function from where i want to return the htm value however i am getting an undefined. I get a return value as i have checked that already.
function loadData(uid) {
$.ajax({
type: "POST",
url: '<%= page.resolveURL("~")%>Haggler.asmx/getLovedProductsSellerStoreByFbId',
//url: '<%= Page.ResolveUrl("~")%>Haggler.asmx/GetFacebookFriends',
data: '{FacebookId:' + uid + ',pageIndex:' + JSON.stringify(pageIndex) + '}',
contentType: "application/json; charset=utf-8",
dataType: 'json',
async: true,
// Page parameter to make sure we load new data
success: function (data) {
var myObject = eval('(' + data.d + ')');
//alert('getProductDescription' + JSON.stringify(myObject));
var html = '';
pageIndex++;
var htmlCategoryList = '';
var i = 0, length = myObject.length;
var _productLink = '';
var _productFullLink = '';
if (length > 0) {
pageCount = myObject[0].PageCount;
if (length > 0) {
for (; i < length; i++) {
if (myObject[i].ShippingQuantity > 0) {
_productLink = myObject[i].SellReqID + '/product/' + myObject[i].CurrentNodeName;
_productFullLink = "http://www.xarato.com/" + myObject[i].SellReqID + "/product/" + myObject[i].CurrentNodeName;
if (myObject[i].Discount == 0) {
/**
if (parts[parts.length-1] == 'loves') {
html += '<li class="polaroid"><div class="prodoptionbg prodseller"><span>Listed by ' + myObject[i].FirstName + ' ' + myObject[i].LastName + '</span></div><a href="/' + _productLink + '"><div style="position:relative;"><img alt="' + myObject[i].NodeName + '" src="/' + myObject[i].
html += '<li class="polaroid"><div style="position:relative;"><img alt="' + myObject[i].RequestTitle + '" src="/' + myObject[i].Image1 + '"_thumb.jpg" width="200" height="' + myObject[i].ThumbHeight1 + '"><div class="options"><span class="favs" id="span' + myObject[i].SellReqID + '">' + myObject[i].Likes + '</span><span class="fav" onclick="calculateLike(event,' + myObject[i].SellReqID + ')">like it!</span></div></div><div class="prod"><span>' + myObject[i].RequestTitle + '</span></div><div class="prodprice1"><span style="font-weight:700;">Rs. ' + Math.round(parseFloat(myObject[i].MRPrice) + parseFloat(myObject[i].ShippingPrice)) + '</span></div></li>';
}else{ **/
//alt="' + myObject[i].RequestTitle + '"
html += '<img alt="' + myObject[i].RequestTitle + '" src="/' + myObject[i].Image1 + '_thumb.jpg" width="200" height="' + myObject[i].ThumbHeight1 + '">';
//}
}
else {
/**if (parts[parts.length-1] == 'loves') {
var _finalPrice = parseFloat(myObject[i].MRPrice) - (parseFloat(myObject[i].Discount) * parseFloat(myObject[i].MRPrice))/100
html += '<li class="polaroid"><div class="prodoptionbg prodseller"><span>Listed by ' + myObject[i].FirstName + ' ' + myObject[i].LastName + '</span></div><div style="position:relative;"><img alt="' + myObject[i].NodeName + '" src="/' + myObject[i].Preview + '_thumb.jpg" width="200" height="' + myObject[i].Height + '"><div class="options"><span class="favs" id="span' + myObject[i].NodeId + '">' + myObject[i].Likes + '</span><span class="fav" onclick="calculateLike(event,' + myObject[i].NodeId + ')">like it!</span></div><div class="kjss"><span>' + myObject[i].Discount + '% Off</span></div></div><div class="prod"><span>' + myObject[i].NodeName + '</span></div><div class="prodprice1"><span style="color:#777777; text-decoration:line-through">Rs. ' + myObject[i].MRPrice + '</span> <span style="font-weight:700;">Rs. ' + Math.round(_finalPrice + parseFloat(myObject[i].ShippingPrice)) + '</span></div></li>';
}else{**/
//alt="' + myObject[i].RequestTitle + '"
html += '<img alt="' + myObject[i].RequestTitle + '" src="/' + myObject[i].Image1 + '_thumb.jpg" width="200" height="' + myObject[i].ThumbHeight1 + '">';
//}
}
}
}
if (clearHtml) {
// $('.bxslider').html('');
//htm = '<li>"' + html + '"</li>';
}
// var htmli = '<li>"' + html + '"</li>';
// $('.bxslider').append(htmli);
htm = '<li>' + html + '</li>';
alert(htm);
return htm;
clearHtml = false;
var options = {
autoResize: true, // This will auto-update the layout when the browser window is resized.
container: $('#main'), // Optional, used for some extra CSS styling
offset: 17, // Optional, the distance between grid items
itemWidth: 225 // Optional, the width of a grid item
};
}
else {
return;
}
}
else {
return;
}
},
failure: function (data) {
alert('failture');
},
error: function (data) {
alert(data.responseText);
}
});
}
This is how i am taking the data but i get an undefined value.
HtmlM += loadData(myObject.data[i].uid);
Please help me out.
Change your loadData to
function loadData(uid, delegate) {
///In ajax instead of return use
delegate(htm);
}
then call like that
loadData(myObject.data[i].uid, function(html){ HtmlM += html ;});
Ajax is asynchronous so you cant just return (yes you can do it synchronous but its not right way)

Categories